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?
Open the Start menu and select Settings. Go to System. In Display, check the Scale and Resolution options, and adjust them to make your screen look proper. Setting to an option labeled (Recommended) is often the best choice.
Setting a JFrame to fill half the screen For instance, if you want to create a JFrame that is half the width and half the height of the screen, you can just divide the dimensions in half, as shown in this code: Dimension screenSize = Toolkit. getDefaultToolkit(). getScreenSize(); aFrame.
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());
}
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With