Java Swing - 检测 JFrame 显示在哪个显示器上

aar*_*art 6 java swing fullscreen jframe

我从这个问题中了解到,您可以GraphicsDevice[]使用以下代码在 Swing 应用程序中获取当前显示:

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gd = ge.getScreenDevices();
Run Code Online (Sandbox Code Playgroud)

我知道从这里我可以自己设置设备,让用户选择要在菜单中使用的设备等。我的目标是检测应用程序当前显示在这些 GraphicsDevices 中的哪一个,因此我可以默认为当前全屏GraphicsDevice 而不会打扰用户。

我正在使用如下代码来全屏显示我的应用程序:

JFrame frame = new JFrame();

// ... when I want to fullscreen:
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
if (gd.isFullScreenSupported()){
    frame.dispose();
    frame.setUndecorated(true);
    frame.setAlwaysOnTop(true);
    gd.setFullScreenWindow(frame);
    frame.setVisible(true);
}
Run Code Online (Sandbox Code Playgroud)

我在 GraphicsDevice 或 GraphicsEnvironment API 中找不到任何内容来获取显示 JFrame 的当前 GraphicsDevice。我知道通过直接定位窗口可能存在黑客攻击(如上面的链接所述),但我想知道是否有更简单/更优雅的解决方案。

San*_*uri 8

GraphicsDevice device = jframe.getGraphicsConfiguration().getDevice()
Run Code Online (Sandbox Code Playgroud)