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 get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024