How to detect the current display with Java?

Yes, you can do this with the Window, Frame and Graphics Configuration classes.

See more here:

  • http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Window.html
  • http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Frame.html
  • http://java.sun.com/j2se/1.5.0/docs/api/java/awt/GraphicsConfiguration.html

java.awt.Window is the base class of all top level windows (Frame, JFrame, Dialog, etc.) and it contains the getGraphicsConfiguration() method that returns the GraphicsConfiguration that window is using. GraphicsConfiguration has the getGraphicsDevice() method which returns the GraphicsDevice that the GraphicsConfiguration belongs to. You can then use the GraphicsEnvironment class to test this against all GraphicsDevices in the system, and see which one the Window belongs to.

Window myWindow = ....
// ...
GraphicsConfiguration config = myWindow.getGraphicsConfiguration();
GraphicsDevice myScreen = config.getDevice();
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
// AFAIK - there are no guarantees that screen devices are in order... 
// but they have been on every system I've used.
GraphicsDevice[] allScreens = env.getScreenDevices();
int myScreenIndex = -1;
for (int i = 0; i < allScreens.length; i++) {
    if (allScreens[i].equals(myScreen))
    {
        myScreenIndex = i;
        break;
    }
}
System.out.println("window is on screen" + myScreenIndex);

The method proposed by Nate does not work when another monitor has just been added to the system and the user repositions the Java window into that monitor. This is a situation my users frequently face, and the only way around it for me has been to restart java.exe to force it to reenumerate the monitors.

The main issue is myWindow.getGraphicsConfiguration().getDevice() always returns the original device where the Java Applet or app was started. You would expect it to show the current monitor, but my own experience (a very time consuming and frustrating one) is that simply relying on myWindow.getGraphicsConfiguration().getDevice() is not foolproof. If someone has a different approach that's more reliable, please let me know.

Performing the match for screens (using the allScreen[i].equals(myScreen) call) then continues to return the original monitor where the Applet was invoked, and not the new monitor where it might have gotten repositioned.

Tags:

Java