Java Toolkit获得第二个屏幕大小

Hum*_*rey 8 java size screen toolkit

我有两个屏幕插入我的电脑,并想知道在JFrame或Toolkit中是否有办法检测窗口在哪个屏幕上?

我有这个代码:

java.awt.Toolkit.getDefaultToolkit().getScreenSize();
Run Code Online (Sandbox Code Playgroud)

这取决于我的主屏幕的屏幕尺寸,但是如何获得第二个屏幕的大小,或者检测窗口所在的屏幕?

Mat*_*Mat 12

你应该看看GraphicsEnvironment.

特别是getScreenDevices():

返回所有屏幕GraphicsDevice对象的数组.

您可以从这些GraphicDevice对象中获取维度(间接地,通过getDisplayMode).(该页面还显示了如何将帧放在特定设备上.)

并且您可以通过该getGraphicsConfigration()方法从JFrame获取其设备,该方法返回具有.的GraphicsConfigurationgetDevice().(该getIDstring()方法可能使您能够区分屏幕.)


Mar*_*aux 6

在StackOverflow上查看此主题.OP中的代码使用此代码:

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());
      }
 }
Run Code Online (Sandbox Code Playgroud)

输出是:

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 
Run Code Online (Sandbox Code Playgroud)

所以,你可以看到它返回两个屏幕.他有两个1024x768的屏幕,彼此相邻.代码可以优化,因为你只需要宽度和高度:

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
for(GraphicsDevice curGs : gs)
{
      DisplayMode dm = curGs.getDisplayMode();
      System.out.println(dm.getWidth() + " x " + dm.getHeight());
}
Run Code Online (Sandbox Code Playgroud)