17

我正在开发一个 Java Swing 应用程序。我怎样才能使它在程序本身和任何其他窗口打开时出现在屏幕中央?

4

5 回答 5

46
frame.setLocationRelativeTo( null );
于 2010-06-21T03:18:25.660 回答
4

frame.setLocationRelativeTo(null); 使框架在 cetner 中打开

问候, Rehan Farooq

于 2013-03-04T12:14:42.547 回答
3

如果您使用的是 Netbeans,这很容易。在 JFrame 的属性窗口中转到“代码”选项卡。有一个选项为“生成中心”。检查该选项。JFrame 将显示在中心。

于 2014-07-24T07:15:38.600 回答
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),但按钮必须已经添加到对话框中,并且可见。

于 2010-06-21T14:04:44.500 回答
1

您必须使用setLocation(x,y).

就像是:

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

应该这样做(未经测试)。

于 2010-06-21T03:44:42.693 回答