如何用Java检测当前显示? [英] How to detect the current display with Java?

查看:95
本文介绍了如何用Java检测当前显示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我连接了2台显示器,因此我可以在主显示器或辅助显示器上启动我的Java应用程序。

I have 2 displays connected, so I can either launch my Java application on the primary or the secondary display.

问题是:我怎么知道哪个显示包含我的应用程序窗口,即有没有办法用Java检测当前显示?

The question is: How can I know which display contains my app window, i.e., is there a way to detect the current display with Java?

推荐答案

java.awt.Window 是基础所有顶级窗口的类(Frame,JFrame,Dialog等),它包含返回 getGraphicsConfiguration()方法窗口正在使用的.sun.com / javase / 6 / docs / api / java / awt / GraphicsConfiguration.htmlrel =noreferrer> GraphicsConfiguration 。 GraphicsConfiguration具有 getGraphicsDevice()方法,该方法返回 GraphicsDevice 。然后,您可以使用 GraphicsEnvironment 类进行测试这针对系统中的所有GraphicsDevices,并查看Window属于哪一个。

java.awt.Window is the base class of all top level windows (Frame, JFrame, Dialog, etc.) and it contains the getGraphicsConfiguration() method that returns the GraphicsConfiguration that window is using. GraphicsConfiguration has the getGraphicsDevice() method which returns the GraphicsDevice that the GraphicsConfiguration belongs to. You can then use the GraphicsEnvironment class to test this against all GraphicsDevices in the system, and see which one the Window belongs to.

Window myWindow = ....
// ...
GraphicsConfiguration config = myWindow.getGraphicsConfiguration();
GraphicsDevice myScreen = config.getDevice();
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
// AFAIK - there are no guarantees that screen devices are in order... 
// but they have been on every system I've used.
GraphicsDevice[] allScreens = env.getScreenDevices();
int myScreenIndex = -1;
for (int i = 0; i < allScreens.length; i++) {
    if (allScreens[i].equals(myScreen))
    {
        myScreenIndex = i;
        break;
    }
}
System.out.println("window is on screen" + myScreenIndex);

这篇关于如何用Java检测当前显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆