java 中开窗

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3081913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 00:17:18  来源:igfitidea点击:

Center Swing Windows

javaswingjframecenterjwindow

提问by Travis

I'm developing a Java Swing application. How can I make it so that when the program itself and any other windows open they come up in the center of the screen?

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

回答by camickr

frame.setLocationRelativeTo( null );

回答by Rehan Farooq

frame.setLocationRelativeTo(null); make the frame open in cetner

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

Regards, Rehan Farooq

问候, Rehan Farooq

回答by Saji

It is easy if you are using Netbeans. In property window of JFrame go to "Code" tab.There is an option as "Generate center".Check that option. JFrame will display in center.

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

回答by Jules Olléon

You'll have to do it by hand, using setLocation(x,y).

您必须手动完成,使用setLocation(x,y).

Something like:

就像是:

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

should do it (not tested).

应该这样做(未测试)。

回答by Taisin

Doing it by hand in multi-screen environment gives something like this (static, 'cause you probably would want it in a utility class):

在多屏幕环境中手动执行会给出类似的结果(静态,因为您可能希望在实用程序类中使用它):

  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);

}

As for default button, it's JDialog.getRootPane().setDefaultButton(btn), but button has to be already added to the dialog, and visible.

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