12 java
我连接了2个显示器,因此我可以在主显示器或辅助显示器上启动我的Java应用程序.
问题是:我怎么知道哪个显示包含我的应用程序窗口,即有没有办法用Java检测当前显示?
Nat*_*ate 24
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);
Run Code Online (Sandbox Code Playgroud)
当另一个监视器刚刚添加到系统中并且用户将Java窗口重新定位到该监视器中时,Nate提出的方法不起作用.这是我的用户经常遇到的情况,对我来说唯一的办法是重启java.exe以强制它重新枚举监视器.
主要问题是myWindow.getGraphicsConfiguration().getDevice()始终返回启动Java Applet或app 的原始设备.您可能希望它显示当前的监视器,但我自己的经验(非常耗时且令人沮丧)只是依赖于myWindow.getGraphicsConfiguration().getDevice()并非万无一失.如果有人采用更可靠的方法,请告诉我.
执行屏幕匹配(使用allScreen [i] .equals(myScreen)调用)然后继续返回调用Applet的原始监视器,而不是新监视器可能重新定位的位置.