简体   繁体   中英

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

I have a jframe when i use

setLocationRelativeTo(null);

the JFrame does not appear at the middle of window why it is so my full code-

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);

My Output is this- 在此处输入图片说明

setLocationRelativeTo(null);

Must be invoked AFTER you have added components to the frame and invoked pack() on the frame, otherwise the frame has a size of (0, 0) so it can't be centered properly.

Edit:

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 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM