中心摇摆窗户

16

我正在开发一个Java Swing 应用程序。如何使得无论是该程序本身还是其他窗口,它们都能够在屏幕中央打开?

5个回答

46
frame.setLocationRelativeTo( null );

这个在较旧版本的Java上也可以工作吗?我感到惊讶,因为一段时间以前我找到的唯一方法是“手动”,正如这里所解释的:http://www.java2s.com/Code/Java/Swing-JFC/Howtocenteraframeordialog.htm - Jules Olléon
1
这在1.4版本中是有效的,但您必须先确保正确地打包或调整屏幕大小。 - Yishai
2
如果你不知道,setLocationRelativeTo()的行为并不是很明显,但是根据javadoc中的描述,当传入null时,它确实会将窗口居中。 - Gnoupi
它没有将窗口居中 - 它在窗口的左上角居中。 - Dan
4
@DanMatthews-Grout,这是因为您需要在调用frame.setLocationRelativeTo(...)之前调用frame.pack()或frame.setSize()。否则,窗口的大小为(0, 0),因此位置将基于该大小。 - camickr
@camickr - 太棒了!谢谢! - Dan

4

frame.setLocationRelativeTo(null); 使窗口在中心位置打开。

祝好, Rehan Farooq


3
如果你使用Netbeans,这就非常简单了。在JFrame的属性窗口中转到"Code"标签页,那里有一个选项叫做"Generate center",勾选它即可。这样,JFrame就会居中显示。

1

你需要手动使用 setLocation(x,y) 来完成它。

类似这样:

Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation((dim.width-frameWidth)/2, (dim.height-frameHeight)/2);

应该可以做到(未经测试)。


1
在多屏幕环境下手动完成它会得到类似这样的结果(静态的,因为您可能希望将其放在实用程序类中):
  public static Rectangle getScreenBounds(Component top){
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice[] gd = ge.getScreenDevices();

    if (top != null){
        Rectangle bounds = top.getBounds();
        int centerX = (int) bounds.getCenterX();
        int centerY = (int) bounds.getCenterY();

        for (GraphicsDevice device : gd){
            GraphicsConfiguration gc = device.getDefaultConfiguration();
            Rectangle r = gc.getBounds();
            if (r.contains(centerX, centerY)){
                return r;
            }
        }
    }
    return gd[0].getDefaultConfiguration().getBounds();
}

public void centerWindowOnScreen(Window windowToCenter){
    Rectangle bounds = getScreenBounds(windowToCenter);
    Point newPt = new Point(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2);
    Dimension componentSize = windowToCenter.getSize();
    newPt.x -= componentSize.width / 2;
    newPt.y -= componentSize.height / 2;
    windowToCenter.setLocation(newPt);

}

对于默认按钮,可以使用JDialog.getRootPane().setDefaultButton(btn),但是按钮必须已经添加到对话框中并且可见。

我在这里使用两个显示器。其中一个甚至是垂直偏移的。camickr/Rehans的答案对我很有效。它将窗口居中于第一个屏幕。难道这不是你的方法所要完成的吗?或者我在这里漏掉了什么吗?谢谢! - Riscie
@Riscie 不是很准确。我的方法是尝试找到您的组件显示在哪个屏幕上,这样您就可以将其居中于该屏幕上,而不仅仅是第一个屏幕。 - Taisin
感谢澄清!这很不错!可惜默认情况下没有提供! - Riscie

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