Search code examples
javaswingjframefullscreen

Java Swing - Detect which display a JFrame is displayed on


I am aware from this question that you can get the current displays as a GraphicsDevice[] in a swing application with the following code:

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gd = ge.getScreenDevices();

I understand that from here I could set the device myself, let the user select which to use in a menu, etc. My goal is to detect which of these GraphicsDevices the application is currently displayed in, so I can default to fullscreening in that current GraphicsDevice without bothering the user.

I am using code like the following to fullscreen my application:

JFrame frame = new JFrame();

// ... when I want to fullscreen:
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
if (gd.isFullScreenSupported()){
    frame.dispose();
    frame.setUndecorated(true);
    frame.setAlwaysOnTop(true);
    gd.setFullScreenWindow(frame);
    frame.setVisible(true);
}

I cannot find anything in the GraphicsDevice or GraphicsEnvironment APIs to get the current GraphicsDevice the JFrame is displayed on. I am aware there may be possible hacks by positioning the window directly (as described in the link above), but I am wondering if there is an easier/more elegant solution.


Solution

  • GraphicsDevice device = jframe.getGraphicsConfiguration().getDevice()