在双监视器配置中的特定屏幕上显示JFrame

我有一个双监视器配置,如果找到它,我想在特定的监视器中运行我的GUI。我试图创建JFrame一个通过GraphicConfiguration屏幕设备对象的窗口,但是它不起作用,框架仍显示在主屏幕上。

如何设置必须显示框架的屏幕?


杨魅力
浏览 338回答 3
3回答

子衿沉夜

public static void showOnScreen( int screen, JFrame frame ){&nbsp; &nbsp; GraphicsEnvironment ge = GraphicsEnvironment&nbsp; &nbsp; &nbsp; &nbsp; .getLocalGraphicsEnvironment();&nbsp; &nbsp; GraphicsDevice[] gs = ge.getScreenDevices();&nbsp; &nbsp; if( screen > -1 && screen < gs.length )&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; gs[screen].setFullScreenWindow( frame );&nbsp; &nbsp; }&nbsp; &nbsp; else if( gs.length > 0 )&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; gs[0].setFullScreenWindow( frame );&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; throw new RuntimeException( "No Screens Found" );&nbsp; &nbsp; }}

慕容3067478

我修改了@ Joseph-gordon的答案,以允许在不强制全屏的情况下实现此目的:public static void showOnScreen( int screen, JFrame frame ) {&nbsp; &nbsp; GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();&nbsp; &nbsp; GraphicsDevice[] gd = ge.getScreenDevices();&nbsp; &nbsp; if( screen > -1 && screen < gd.length ) {&nbsp; &nbsp; &nbsp; &nbsp; frame.setLocation(gd[screen].getDefaultConfiguration().getBounds().x, frame.getY());&nbsp; &nbsp; } else if( gd.length > 0 ) {&nbsp; &nbsp; &nbsp; &nbsp; frame.setLocation(gd[0].getDefaultConfiguration().getBounds().x, frame.getY());&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; throw new RuntimeException( "No Screens Found" );&nbsp; &nbsp; }}在这段代码中,我假设getDefaultConfiguration()永远不会返回null。如果不是这种情况,请有人纠正我。但是,此代码可将您JFrame移至所需的屏幕。

qq_笑_17

阅读屏幕2上有关JFrame.setLocationRelativeTo的文档后,一种更清洁的解决方案public void moveToScreen() {&nbsp; &nbsp; setVisible(false);&nbsp; &nbsp; GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();&nbsp; &nbsp; GraphicsDevice[] screens = ge.getScreenDevices();&nbsp; &nbsp; int n = screens.length;&nbsp; &nbsp; for (int i = 0; i < n; i++) {&nbsp; &nbsp; &nbsp; &nbsp; if (screens[i].getIDstring().contentEquals(settings.getScreen())) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; JFrame dummy = new JFrame(screens[i].getDefaultConfiguration());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setLocationRelativeTo(dummy);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dummy.dispose();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; setVisible(true);}此功能可用于在屏幕之间切换应用程序窗口
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java