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.
            //
            e.printStackTrace();
        }
    }
}

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply