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.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 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();
}
}
}
The output of the code snippet above:
Number of available screens = 2
Latest posts by Wayan (see all)
- How do I convert Map to JSON and vice versa using Jackson? - June 12, 2022
- How do I find Java version? - March 21, 2022
- How do I convert CSV to JSON string using Jackson? - February 13, 2022