Detect if monitor is rotated

I have an application in JavaSE and I want my application to always start in the center of the screen. If two monitors are connected, use the right one. So I wrote this code:

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); if(ge.getScreenDevices().length == 2) { int w_1 = ge.getScreenDevices()[0].getDisplayMode().getWidth(); int h_1 = ge.getScreenDevices()[0].getDisplayMode().getHeight(); int w_2 = ge.getScreenDevices()[1].getDisplayMode().getWidth(); int h_2 = ge.getScreenDevices()[1].getDisplayMode().getHeight(); int x = w_1 + w_2 / 2 - getWidth() / 2; int y = h_2 / 2 - getHeight() / 2; setLocation(x, y); } 

Unfortunately, if the monitor is rotated 90 ยฐ, the width and height must be turned upside down. Is there any way to detect such a rotation?

+4
source share
3 answers

You do not need to know if the second monitor is in portrait mode. Just find the borders of the screen in the coordinates of the device and use the center. (If it is in portrait mode, then height> width, but this is not important information).

Your formula for determining the center point of the second device is incorrect. You assume that the coordinates of the second screen are from (w_1,0) to (w_1 + w_2, h_2), but this is not necessarily true. You need to find the GraphicsConfiguration object of the second screen and call GraphicsConfiguration.getBounds () on it. Then you can calculate the center point of this rectangle.

If you want to know which device is on the left or right (either top or bottom), you can compare the x (or y) values โ€‹โ€‹of their bounding boxes. Note that x or y values โ€‹โ€‹may be negative.

+2
source

You must consider if the height is greater than the width (portrait). I have not heard anyone use portraits.

+1
source

Here is the code that works fine in most cases (from Enwired answer).

 GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); if(ge.getScreenDevices().length == 2) { int x = (int)ge.getScreenDevices()[1].getDefaultConfiguration().getBounds().getCenterX() - frame.getWidth() / 2; int y = (int)ge.getScreenDevices()[1].getDefaultConfiguration().getBounds().getCenterY() - frame.getHeight() / 2; setLocation(x, y); } 

The only problem is that the device index is not always equal to 0 - left, 1 - right.

+1
source

All Articles