Java Toolkit获得第二个屏幕大小
我有两个屏幕插入我的电脑,并想知道在JFrame或Toolkit中是否有办法检测窗口在哪个屏幕上?
我有这个代码:
java.awt.Toolkit.getDefaultToolkit().getScreenSize();
这会得到我主屏幕的屏幕尺寸,但是如何获得第二个屏幕的大小,或者检测窗口所在的屏幕?
你应该看看GraphicsEnvironment 。
特别是getScreenDevices()
:
返回所有屏幕GraphicsDevice对象的数组。
您可以从这些GraphicDevice对象获取维度(间接地,通过getDisplayMode
)。 (该页面还显示了如何在特定设备上放置框架。)
您可以通过getGraphicsConfigration()
方法从JFrame获取其设备,该方法返回具有getDevice()
的GraphicsConfiguration 。 ( getIDstring()
方法可能使您能够区分屏幕。)
在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
所以,你可以看到它返回两个屏幕。 他有两个1024×768的屏幕,彼此相邻。 代码可以优化,因为你只需要宽度和高度:
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice[] gs = ge.getScreenDevices(); for(GraphicsDevice curGs : gs) { DisplayMode dm = curGs.getDisplayMode(); System.out.println(dm.getWidth() + " x " + dm.getHeight()); }
如果使用此处显示的代码,则可以迭代系统中的所有GraphicsDevice
并获取其尺寸。 鉴于您可以在特定的GraphicsDevice上创建JFrame,您还可以通过获取JFrame的Window来获取特定的GraphicsDevice JFrame,并调用http://download.oracle.com/javase/6/docs/api/java/awt /Window.html#getGraphicsConfiguration ()在Window上然后调用getGraphicsDevice
。
直接到代码,试试这个:)
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 }