ivan_ivanovich_ivanoff
ivan_ivanovich_ivanoff

Reputation: 19453

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

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:

Upvotes: 20

Views: 7589

Answers (2)

bobeojoe
bobeojoe

Reputation: 21

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;
}

Upvotes: 2

z  -
z -

Reputation: 7168

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());
} 

Upvotes: 23

Related Questions