Working with multiple screens in Java

When you want to set the location of a Java Window, you just call setLocation(int x, int y). But what if your screen isn’t big enough? Or when you want to display the window on a second screen?

The desktop is represented by a virtual device, with physical screens providing a viewport onto that device. The top-left corner of the primary screen is always located at coordicates (0, 0). Other physical screens are located relative to this coordinate. See the api-documentation for java.awt.Frame for more information.

To get all available graphics devices, which represent physical screens, use the following code:

GraphicsDevice[] graphicsDevices = 
    GraphicsEnvironment
        .getLocalGraphicsEnvironment()
        .getScreenDevices();

Then, to get the bounds or the offset and size of each device, use the following code:

Rectangle bounds = 
    device
        .getDefaultConfiguration()
        .getBounds();

This works for all screens _except_ the primary screen. The primary screen also contains a taskbar, and you usually don’t want to place a window over the taskbar.

To get the bounds of the primary screen, without the taskbar, use the following code:

GraphicsEnvironment
    .getLocalGraphicsEnvironment()
    .getMaximumWindowBounds();

Leave a Reply

Your email address will not be published. Required fields are marked *