微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将 JFrame 居中?

如何解决如何将 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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。