Java Toolkit获得第二个屏幕大小

时间:2011-06-12 15:01:59

标签: java size screen toolkit

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

我有这段代码:

java.awt.Toolkit.getDefaultToolkit().getScreenSize();

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

4 个答案:

答案 0 :(得分:13)

你应该看看GraphicsEnvironment

特别是getScreenDevices()

  

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

您可以从GraphicDevice个对象获取维度(间接地,通过getDisplayMode)。 (该页面还显示了如何在特定设备上放置框架。)

您可以通过getGraphicsConfigration()方法从JFrame到其设备,该方法返回GraphicsConfiguration,其getDevice()。 (getIDstring()方法可能使您能够区分屏幕。)

答案 1 :(得分:7)

结帐this thread on 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());
      }
 }

输出结果为:

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 

所以,你可以看到它返回两个屏幕。他有两个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());
}

答案 2 :(得分:1)

如果您使用显示here的代码,则可以迭代系统中的所有GraphicsDevice并获取其尺寸。鉴于您可以在特定的GraphicsDevice上创建JFrame,您还可以通过获取JFrame的Window,在Window上调用http://download.oracle.com/javase/6/docs/api/java/awt/Window.html#getGraphicsConfiguration()然后在其上调用getGraphicsDevice来获取特定的GraphicsDevice JFrame。

答案 3 :(得分:0)

直接代码,试试这个:)

    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
    }