Java: Getting resolutions of one/all available monitors (instead of the whole desktop)?
Asked Answered
B

2

20

I have two different-sized monitors, connected together using (I believe) TwinView.

I tried

System.out.println(Toolkit.getDefaultToolkit().getScreenSize());

and get

java.awt.Dimension[width=2960,height=1050]

which is true if you count both monitors together.

Instead of this, I would like to be able achieving one of the following:

  • getting resolution of the current monitor
  • getting resolution of the main monitor
Bartel answered 18/5, 2009 at 12:50 Comment(0)
I
23

you'll want to use the GraphicsEnvironment.

In particular, getScreenDevices() returns an array of GraphicsDevice objects from which you can read the width/height of the display mode.

Example:

GraphicsEnvironment g = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] devices = g.getScreenDevices();

for (int i = 0; i < devices.length; i++) {
    System.out.println("Width:" + devices[i].getDisplayMode().getWidth());
    System.out.println("Height:" + devices[i].getDisplayMode().getHeight());
} 
Impatiens answered 18/5, 2009 at 12:58 Comment(0)
S
2

I came accross this thread when trying to implement a way to capture all screens on any given computer in a single screenshot, and could not find an answer as to how to accomplish this anywhere else.

In my case, Toolkit.getDefaultToolkit().getScreenSize() would only return the resolution of the primary monitor. I made the following method to create a Rectangle that has an origin at the top-leftmost point between all monitors, and is large enough to capture all the content on all the monitors supplied by GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices() when passed to Robot().createScreenCapture.

private Rectangle allScreensRectangle()
{
    // make array of all screens
    GraphicsDevice[] screens = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
    
    // start out with the rectangle of the primary monitor
    Rectangle allScreens = screens[0].getDefaultConfiguration().getBounds();
    for (int i = 1; i < screens.length; i++)
    {
        Rectangle screenRect = screens[i].getDefaultConfiguration().getBounds();

        // expand the size of the capture region to include any area in the x/y dimension that is outside the already-defined rectangle
        allScreens.width += (screenRect.width - (screenRect.width - Math.abs(screenRect.x)));
        allScreens.height += (screenRect.height - (screenRect.height - Math.abs(screenRect.y)));

        // ensure the origin point is always at the top-leftmost point of all monitors.
        allScreens.x = Math.min(allScreens.x, screenRect.x);
        allScreens.y = Math.min(allScreens.y, screenRect.y);
    }
    return allScreens;
}
Slumberland answered 30/10, 2023 at 20:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.