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 create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023