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

blo*_*low 43 java swing multiple-monitors jframe

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

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

Jos*_*don 36

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

  • 但为什么这与"全屏"有关?如果我不需要使用全屏模式怎么办? (3认同)

ryv*_*age 33

我修改了@ Joseph-gordon的答案,以便在不强制全屏的情况下实现这一目标:

public static void showOnScreen( int screen, JFrame frame ) {
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice[] gd = ge.getScreenDevices();
    if( screen > -1 && screen < gd.length ) {
        frame.setLocation(gd[screen].getDefaultConfiguration().getBounds().x, frame.getY());
    } else if( gd.length > 0 ) {
        frame.setLocation(gd[0].getDefaultConfiguration().getBounds().x, frame.getY());
    } else {
        throw new RuntimeException( "No Screens Found" );
    }
}
Run Code Online (Sandbox Code Playgroud)

在这段代码中,我假设getDefaultConfiguration()永远不会返回null.如果不是这样,那么请有人纠正我.但是,此代码可以将您移动JFrame到所需的屏幕.

  • 此解决方案仅在设备未垂直对齐时才有效.将`frame.getY()`替换为`gd [0] .getDefaultConfiguration().getBounds().y + frame.getY()`来解决这个问题. (4认同)

Ger*_*doy 6

我修改了 @Joseph-gordon 和 @ryvantage 答案,以允许一种方法来实现此目的,而无需强制全屏、固定屏幕配置位置并将其置于选择屏幕上:

public void showOnScreen(int screen, JFrame frame ) {
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice[] gd = ge.getScreenDevices();
    int width = 0, height = 0;
    if( screen > -1 && screen < gd.length ) {
        width = gd[screen].getDefaultConfiguration().getBounds().width;
        height = gd[screen].getDefaultConfiguration().getBounds().height;
        frame.setLocation(
            ((width / 2) - (frame.getSize().width / 2)) + gd[screen].getDefaultConfiguration().getBounds().x, 
            ((height / 2) - (frame.getSize().height / 2)) + gd[screen].getDefaultConfiguration().getBounds().y
        );
        frame.setVisible(true);
    } else {
        throw new RuntimeException( "No Screens Found" );
    }
}
Run Code Online (Sandbox Code Playgroud)