如何在 Java 中居中窗口?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/144892/
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-08-11 08:53:05  来源:igfitidea点击:

How to center a Window in Java?

javaswinguser-interfaceawt

提问by Andrew Swan

What's the easiest way to centre a java.awt.Window, such as a JFrameor a JDialog?

将 a 居中的最简单方法是什么java.awt.Window,例如 aJFrame或 a JDialog

采纳答案by Andrew Swan

From this link

这个链接

If you are using Java 1.4 or newer, you can use the simple method setLocationRelativeTo(null) on the dialog box, frame, or window to center it.

如果您使用的是 Java 1.4 或更新版本,则可以在对话框、框架或窗口上使用简单的方法 setLocationRelativeTo(null) 将其居中。

回答by Dónal

This should work in all versions of Java

这应该适用于所有版本的 Java

public static void centreWindow(Window frame) {
    Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
    int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
    frame.setLocation(x, y);
}

回答by Kevin Day

Note that both the setLocationRelativeTo(null) and Tookit.getDefaultToolkit().getScreenSize() techniques work only for the primary monitor. If you are in a multi-monitor environment, you may need to get information about the specific monitor the window is on before doing this kind of calculation.

请注意, setLocationRelativeTo(null) 和 Tookit.getDefaultToolkit().getScreenSize() 技术仅适用于主监视器。如果您处于多显示器环境中,则在进行此类计算之前,您可能需要获取有关窗口所在的特定显示器的信息。

Sometimes important, sometimes not...

有时重要,有时不...

See GraphicsEnvironment javadocsfor more info on how to get this.

有关如何获得它的更多信息,请参阅GraphicsEnvironment javadocs

回答by Thulani Chivandikwa

frame.setLocationRelativeTo(null);

frame.setLocationRelativeTo(null);

Full example:

完整示例:

public class BorderLayoutPanel {

    private JFrame mainFrame;
    private JButton btnLeft, btnRight, btnTop, btnBottom, btnCenter;

    public BorderLayoutPanel() {
        mainFrame = new JFrame("Border Layout Example");
        btnLeft = new JButton("LEFT");
        btnRight = new JButton("RIGHT");
        btnTop = new JButton("TOP");
        btnBottom = new JButton("BOTTOM");
        btnCenter = new JButton("CENTER");
    }

    public void SetLayout() {
        mainFrame.add(btnTop, BorderLayout.NORTH);
        mainFrame.add(btnBottom, BorderLayout.SOUTH);
        mainFrame.add(btnLeft, BorderLayout.EAST);
        mainFrame.add(btnRight, BorderLayout.WEST);
        mainFrame.add(btnCenter, BorderLayout.CENTER);
        //        mainFrame.setSize(200, 200);
        //        or
        mainFrame.pack();
        mainFrame.setVisible(true);

        //take up the default look and feel specified by windows themes
        mainFrame.setDefaultLookAndFeelDecorated(true);

        //make the window startup position be centered
        mainFrame.setLocationRelativeTo(null);

        mainFrame.setDefaultCloseOperation(mainFrame.EXIT_ON_CLOSE);
    }
}

回答by Jonathan Caraballo

The following doesn't work for JDK 1.7.0.07:

以下不适用于 JDK 1.7.0.07:

frame.setLocationRelativeTo(null);

It puts the top left corner at the center - not the same as centering the window. The other one doesn't work either, involving frame.getSize() and dimension.getSize():

它将左上角放在中心 - 与居中窗口不同。另一个也不起作用,涉及 frame.getSize() 和 dimension.getSize():

Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
frame.setLocation(x, y);

The getSize() method is inherited from the Component class, and therefore frame.getSize returns the size of the window as well. Thus subtracting half the vertical and horizontal dimensions from the vertical and horizontal dimensions, to find the x,y coordinates of where to place the top-left corner, gives you the location of the center point, which ends up centering the window as well. However, the first line of the above code is useful, "Dimension...". Just do this to center it:

getSize() 方法继承自 Component 类,因此 frame.getSize 也返回窗口的大小。因此,从垂直和水平尺寸中减去垂直和水平尺寸的一半,以找到放置左上角的位置的 x,y 坐标,为您提供中心点的位置,最终也使窗口居中。但是,上面代码的第一行很有用,“维度...”。只需这样做即可将其居中:

Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension( (int)dimension.getWidth() / 2, (int)dimension.getHeight()/2 ));
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
frame.setLocation((int)dimension.getWidth()/4, (int)dimension.getHeight()/4);

The JLabel sets the screen-size. It's in FrameDemo.java available on the java tutorials at the Oracle/Sun site. I set it to half the screen size's height/width. Then, I centered it by placing the top left at 1/4 of the screen size's dimension from the left, and 1/4 of the screen size's dimension from the top. You can use a similar concept.

JLabel 设置屏幕大小。它位于 Oracle/Sun 站点上的 Java 教程中的 FrameDemo.java 中。我将其设置为屏幕尺寸高度/宽度的一半。然后,我通过将左上角放置在距左侧屏幕尺寸尺寸的 1/4 处以及距顶部屏幕尺寸尺寸的 1/4 处,将其居中。您可以使用类似的概念。

回答by Viswanath Lekshmanan

Actually frame.getHeight()and getwidth()doesnt return values , check it by System.out.println(frame.getHeight());directly put the values for width and height ,then it will work fine in center. eg: as below

实际上 frame.getHeight()getwidth()没有返回值,通过System.out.println(frame.getHeight());直接输入 width 和 height 的值来检查它,然后它会在中心正常工作。例如:如下

Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();      
int x=(int)((dimension.getWidth() - 450)/2);
int y=(int)((dimension.getHeight() - 450)/2);
jf.setLocation(x, y);  

both 450 is my frame width n height

450 都是我的框架宽度 n 高度

回答by Dzmitry Sevkovich

setLocationRelativeTo(null)should be called after you either use setSize(x,y), or use pack().

setLocationRelativeTo(null)应该在您使用setSize(x,y)或使用之后调用pack()

回答by Peter Szabo

On Linux the code

在 Linux 上的代码

setLocationRelativeTo(null)

Put my window to random location each time I launched it, in a multi display environment. And the code

在多显示环境中,每次启动它时,将我的窗口放在随机位置。和代码

setLocation((Toolkit.getDefaultToolkit().getScreenSize().width  - getSize().width) / 2, (Toolkit.getDefaultToolkit().getScreenSize().height - getSize().height) / 2);

"cut" the window in half with placing it to the exact center, which is between my two displays. I used the following method to center it:

将窗口“切割”成两半,并将其放置在我的两个显示器之间的确切中心。我使用以下方法将其居中:

private void setWindowPosition(JFrame window, int screen)
{        
    GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice[] allDevices = env.getScreenDevices();
    int topLeftX, topLeftY, screenX, screenY, windowPosX, windowPosY;

    if (screen < allDevices.length && screen > -1)
    {
        topLeftX = allDevices[screen].getDefaultConfiguration().getBounds().x;
        topLeftY = allDevices[screen].getDefaultConfiguration().getBounds().y;

        screenX  = allDevices[screen].getDefaultConfiguration().getBounds().width;
        screenY  = allDevices[screen].getDefaultConfiguration().getBounds().height;
    }
    else
    {
        topLeftX = allDevices[0].getDefaultConfiguration().getBounds().x;
        topLeftY = allDevices[0].getDefaultConfiguration().getBounds().y;

        screenX  = allDevices[0].getDefaultConfiguration().getBounds().width;
        screenY  = allDevices[0].getDefaultConfiguration().getBounds().height;
    }

    windowPosX = ((screenX - window.getWidth())  / 2) + topLeftX;
    windowPosY = ((screenY - window.getHeight()) / 2) + topLeftY;

    window.setLocation(windowPosX, windowPosY);
}

Makes the window appear right at the center of the first display. This is probably not the easiest solution.

使窗口出现在第一个显示的正中央。这可能不是最简单的解决方案。

Works properly on Linux, Windows and Mac.

在 Linux、Windows 和 Mac 上正常工作。

回答by borchvm

public class SwingExample implements Runnable {

    @Override
    public void run() {
        // Create the window
        final JFrame f = new JFrame("Hello, World!");
        SwingExample.centerWindow(f);
        f.setPreferredSize(new Dimension(500, 250));
        f.setMaximumSize(new Dimension(10000, 200));
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void centerWindow(JFrame frame) {
        Insets insets = frame.getInsets();
        frame.setSize(new Dimension(insets.left + insets.right + 500, insets.top + insets.bottom + 250));
        frame.setVisible(true);
        frame.setResizable(false);

        Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
        int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
        frame.setLocation(x, y);
    }
}

回答by Julien

The following code center the Windowin the center of the current monitor (ie where the mouse pointer is located).

以下代码Window将 居中在当前监视器的中心(即鼠标指针所在的位置)。

public static final void centerWindow(final Window window) {
    GraphicsDevice screen = MouseInfo.getPointerInfo().getDevice();
    Rectangle r = screen.getDefaultConfiguration().getBounds();
    int x = (r.width - window.getWidth()) / 2 + r.x;
    int y = (r.height - window.getHeight()) / 2 + r.y;
    window.setLocation(x, y);
}