I have two monitors
I write very small Swing Java code to collect info of all screen devices combine changing display mode with one or two display screen by setting Display in Control Panel.
And code like below:
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
final JFrame frame = new JFrame("Demo get info screen devices");
JButton button = new JButton("Print info screen devices");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
printInfoAllScreenDevices();
}
});
frame.add(button);
frame.setSize(500, 300);
frame.setVisible(true);
}
private static void printInfoAllScreenDevices() {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] graphicsDevices = ge.getScreenDevices();
System.out.println("Number of screen devices:" + graphicsDevices.length);
}
}
First I start program with two screens and then I click to button ("Print info screen devices"). In output shows
Number of screen devices:2
Correct!
Next I changed to one display mode. Finally, click button again and result still 2. Actually only 1 screen device.
I check that GraphicsEnvironment.getLocalGraphicsEnvironment() create a instance like singleton. It means can not update? One more thing, I don't want close programe and open again.
How can I get right information of screen devices like this case?
And I also want Java will decide which class (extend GraphicsEnvironment) provide info of screen devices, depend on operation system.
Thanks for your advance!
It may be tricky. But from a quick look at the source code, you might try some reflection.
The following is an example showing how this might work: