How do I get number of available screens?

This code shows how to get number of available screen devices on the local machine or local graphics environment. We obtain the number of screens by getting the length of array returned by GraphicsEnvironment.getScreenDevices() method.

This process can produce a HeadlessException to happen if we try to run this code on a machine that doesn’t have a screen device with it.

package org.kodejava.example.awt;

import java.awt.GraphicsEnvironment;
import java.awt.GraphicsDevice;
import java.awt.HeadlessException;

public class GettingNumberOfScreen {
    public static void main(String[] args) {
        try {
            // Get local graphics environment
            GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();

            // Returns an array of all of the screen GraphicsDevice objects.
            GraphicsDevice[] devices = env.getScreenDevices();

            int numberOfScreens = devices.length;
            System.out.println("Number of available screens = " + numberOfScreens);
        } catch (HeadlessException e) {
            // We'll get here if no screen devices was found.

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🥳

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.