如何将 JFrame 居中?

问题描述

我知道另一个人已经问过这个问题了。答案应该是 frame.setLocationRelativeTo(null);,但是当我尝试使用此方法时,JFrame 最终出现在屏幕的右下角。为什么会这样,我还应该怎么做才能使 JFrame 居中?

下面的第一件事是我写的代码(顺便说一句,我正在编写一个动物翻译器),第二件事是我运行代码时所发生情况的图像链接。

import java.awt.BorderLayout;
import java.awt.GridLayout;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class AnimaleseTranslator {
    public static void main(String[] args) {        
        JFrame frame = new JFrame();        
        JPanel panel = new JPanel();
        panel.setBorder(BorderFactory.createEmptyBorder(220,391,220,391));
        panel.setLayout(new GridLayout(0,1));      
        frame.add(panel,BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setTitle("Animalese Translator");
        frame.pack();
        frame.setVisible(true);     
    }
}

The JFrame is supposed to be in the center of the screen since I wrote the frame.setLocationRelativeTo(null); line,but instead it is in the bottom right corner of the screen.

解决方法

您应该在 pack 之前调用 setLocationRelativeTo

frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...