问题描述
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);
我的输出是这个-
解决方法
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 );