簡體   English   中英

不能使用 setLocationRelativeTo(null) 使 Jframe 居中;

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

我使用時有一個 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", 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 );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM