无法使用 setLocationRelativeTo(null) 使 Jframe 居中;

can't make Jframe in center using setLocationRelativeTo(null);

我用的时候有个jframe

setLocationRelativeTo(null);

JFrame 没有出现在 window 为什么会这样 我的完整代码-

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", Font.BOLD, 50));
bu.setBorderPainted(false);
bu2.setForeground(Color.WHITE);
bu2.setBackground(Color.BLACK);
bu2.setFont(new Font("serif", Font.BOLD, 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 );