I have two screens plugged into my computer and was wondering if there was a way in JFrame or Toolkit of detecting which screen the window is on?
I have this code:
java.awt.Toolkit.getDefaultToolkit().getScreenSize();
Which gets my screen size of my main screen, but how can I get the size of my second screen, or detect which screen the window is on?
You should take a look at GraphicsEnvironment.
In particular, getScreenDevices()
:
Returns an array of all of the screen GraphicsDevice objects.
You can get the dimensions from those GraphicDevice objects (indirectly, via getDisplayMode
). (That page also shows how to put a frame on a specific device.)
And you can get from a JFrame to its device via the getGraphicsConfigration()
method, which returns a GraphicsConfiguration that has a getDevice()
. (The getIDstring()
method will probably enable you to differentiate between the screens.)
Check out this thread on StackOverflow. The code in from the OP uses this code:
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
for(GraphicsDevice curGs : gs)
{
GraphicsConfiguration[] gc = curGs.getConfigurations();
for(GraphicsConfiguration curGc : gc)
{
Rectangle bounds = curGc.getBounds();
System.out.println(bounds.getX() + "," + bounds.getY() + " " + bounds.getWidth() + "x" + bounds.getHeight());
}
}
The output was:
0.0,0.0 1024.0x768.0
0.0,0.0 1024.0x768.0
0.0,0.0 1024.0x768.0
0.0,0.0 1024.0x768.0
0.0,0.0 1024.0x768.0
0.0,0.0 1024.0x768.0
1024.0,0.0 1024.0x768.0
1024.0,0.0 1024.0x768.0
1024.0,0.0 1024.0x768.0
1024.0,0.0 1024.0x768.0
1024.0,0.0 1024.0x768.0
1024.0,0.0 1024.0x768.0
So, you can see it returns two screens. He had two screens of 1024x768, positioned next to each other.
The code can be optimized to, since you only want width and height:
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
for(GraphicsDevice curGs : gs)
{
DisplayMode dm = curGs.getDisplayMode();
System.out.println(dm.getWidth() + " x " + dm.getHeight());
}
If you use the code shown here you can iterate over all the GraphicsDevice
s in the system and get their dimensions. Given that you can create a JFrame on a specific GraphicsDevice you can also fetch the specific GraphicsDevice a JFrame is on by getting the JFrame's Window, calling http://download.oracle.com/javase/6/docs/api/java/awt/Window.html#getGraphicsConfiguration() on the Window and then calling getGraphicsDevice
on that.
Straight to the code, try this :)
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
for (int i = 0; i < gs.length; i++) {
System.out.println(gs[i].getDisplayMode().getWidth()+" "+gs[i].getDisplayMode().getHeight());
//System.out.println(java.awt.Toolkit.getDefaultToolkit().getScreenSize());
// to check default resolution of the device
}