如何用Java检测当前显示?

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

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

java.awt.Window是所有顶级窗口(Frame,JFrame,Dialog等)的基类,它包含getGraphicsConfiguration()方法,该方法返回窗口正在使用的GraphicsConfiguration 。 GraphicsConfiguration具有getGraphicsDevice()方法,该方法返回GraphicsConfiguration所属的GraphicsDevice。 然后,您可以使用GraphicsEnvironment类对系统中的所有GraphicsDevices进行测试,并查看Window所属的那个。

 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窗口重新定位到该监视器中时,Nate提出的方法不起作用。 这是我的用户经常遇到的情况,对我来说唯一的办法是重启java.exe以强制它重新枚举监视器。

主要问题是myWindow.getGraphicsConfiguration()。getDevice()始终返回启动Java Applet或app的原始设备。 您可能希望它显示当前的监视器,但我自己的经验(非常耗时且令人沮丧)只是依赖于myWindow.getGraphicsConfiguration()。getDevice()并非万无一失。 如果有人采用更可靠的方法,请告诉我。

执行屏幕匹配(使用allScreen [i] .equals(myScreen)调用)然后继续返回调用Applet的原始监视器,而不是新监视器可能重新定位的位置。

Nate的解决方案似乎适用于大多数情况 ,但不是所有情况,因为我必须经历。 困惑的提到他在显示器连接时遇到问题,我遇到了“Win + Left”和“Win + Right”键命令的问题。 我对问题的解决方案看起来像这样(也许解决方案本身就有问题,但至少这对我来说比Nate的解决方案更好):

 GraphicsDevice myDevice = myFrame.getGraphicsConfiguration().getDevice(); for(GraphicsDevice gd:GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()){ if(frame.getLocation().getX() >= gd.getDefaultConfiguration().getBounds().getMinX() && frame.getLocation().getX() < gd.getDefaultConfiguration().getBounds().getMaxX() && frame.getLocation().getY() >= gd.getDefaultConfiguration().getBounds().getMinY() && frame.getLocation().getY() < gd.getDefaultConfiguration().getBounds().getMaxY()) myDevice=gd; }