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

无法使用setLocationRelativeTonull使Jframe居中

如何解决无法使用setLocationRelativeTonull使Jframe居中

使用时我有一个jframe

setLocationRelativeto(null);

为什么JFrame不会出现在窗口中间 我的完整代码-

JFrame ca = new JFrame("Start");
ca.setUndecorated(true);
ca.setLocationRelativeto(null);
JLabel lab = new JLabel("   Space Invaders");
JButton bu = new JButton("START");
JButton bu2 = new JButton("QUIT");
lab.setFont(new Font("Serif Italic",Font.BOLD,60));
lab.setForeground(Color.RED);
bu.setForeground(Color.WHITE);
bu.setBackground(Color.BLACK);
bu.setFont(new Font("serif",50));
bu.setBorderPainted(false);
bu2.setForeground(Color.WHITE);
bu2.setBackground(Color.BLACK);
bu2.setFont(new Font("serif",50));
bu2.setBorderPainted(false);

我的输出是这个-

enter image description here

解决方法

setLocationRelativeTo(null);

必须在将组件添加到框架并在框架上调用pack()之后再调用,否则框架的大小为(0,0),因此无法正确居中。

编辑:

JFrame frame = new JFrame(...);
frame.add(someComponent);
frame.add(anotherComponent);
frame.pack(); // now the frame width/height is greater than 0.
frame.setLocationRelativeTo( null );
frame.setVisible( true );

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