在第二个屏幕或显示器上居中JFrame - Java

3

我正在尝试在第二个屏幕上打开一个JFrame并将其居中。我可以在第二个屏幕上打开JFrame,但如何将其居中呢?以下是我编写的示例代码:

import javax.swing.*;
import java.awt.*;

public class Question {

public Question() {
    JFrame f = new JFrame();
    JPanel panel = new JPanel();
    f.getContentPane().add(panel);
    f.pack();
    f.setTitle("Hello");
    f.setSize(200,200);
    showOnScreen(1,f);
    f.setVisible(true);
}

public static void main(String[] args) {
    Runnable r = new Runnable() {
        @Override
        public void run() {
            new Question();
        }
    };
    SwingUtilities.invokeLater(r);
}
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" );
    }
}

}

我尝试了以下类似的方法来在第二个屏幕上居中显示它:
frame.setLocation((gd[screen].getDefaultConfiguration().getBounds().x*3/2)-200, ((gd[screen].getDefaultConfiguration().getBounds().height)/2)-200);

它可以工作,但我不想硬编码大小,因为在实际程序中,框架大小可能会改变。

另外,我尝试了这个:

frame.setLocation((gd[screen].getDefaultConfiguration().getBounds().width)/2-frame.getSize().width/2, (gd[screen].getDefaultConfiguration().getBounds().height)/2-frame.getSize().height/2);

但是它会在第一个屏幕上打开。这很合理。 请有人帮忙应用正确的修复方法。感谢您的帮助。谢谢。

f.setVisible() 之前或之后放置 f.setLocationRelativeTo(null); - Madhan
然后它在第一个屏幕上打开了框架。我希望它在第二个屏幕上打开并居中显示。 - user2100513
请参考此链接:https://dev59.com/hG445IYBdhLWcg3w7ug0 - Madhan
谢谢Madhan。那是我之前参考过的页面。我找到了解决方案。请查看下面。如果您发现任何问题,请告诉我。 - user2100513
只要它解决了你的问题,那就可以。 - Madhan
2个回答

2
这是我的解决方法。我的应用程序最多可以有两个屏幕。
  public void showOnScreen( int screen, JFrame frame ) {
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice[] gd = ge.getScreenDevices();
    if( screen > 0 && screen < 2 ) {
        int x = frame.getWidth()/2;
        int y = frame.getHeight()/2;
        frame.setLocation((gd[screen].getDefaultConfiguration().getBounds().width * 3/2) - x,   (gd[screen].getDefaultConfiguration().getBounds().height *1/2) - y);
    } else if( gd.length > 0 ) {
        frame.setLocationRelativeTo(null);
    } else {
        throw new RuntimeException( "No Screens Found" );
    }
}

1
为了在第二个屏幕上显示居中(在此示例中为最后一个屏幕),我做了以下操作:
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gd = ge.getScreenDevices();
GraphicsConfiguration gc = gd[gd.length - 1].getDefaultConfiguration();
frame.setLocationRelativeTo(new JFrame(gd));

根据setLocationRelativeTo(Component c)文档: 如果组件不为空,但当前未显示,则窗口将放置在与此组件关联的GraphicsConfiguration定义的目标屏幕的中心位置。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接