我有一個程序,我有一個JFrame
其中JButton
。當用戶單擊JButton
時,將刪除JFrame
的所有Components
,並向其添加帶有紅色背景的JPanel
。如何在JFrame可見時將組件添加到JFrame中,而無需調整它的大小?
當我點擊JButton
時,除非我調整JFrame
(我正在使用Windows 7)的大小,否則該紅色JPanel
不可見。有沒有辦法實現我想要的而不必手動調整JFrame
的大小?
這裏是我使用的代碼的一部分:
public class Demo implements ActionListener{
public static void main(String args[]){
...............
button.addActionListener(this); //'button' is an object of Jbutton class.
frame.setVisible(true); //'frame' is an object of JFrame class.
............
}
public void actionPerformed(ActionEvent ae){
frame.removeAllComponents();
frame.add(panel1); //panel1 is an object of Jpanel class with red background.
/* Here is where my problem lies.
panel1 is not visible to me unless I manually resize the JFrame. */
}
}
考慮使用'CardLayout'。參見[E.G.](http://stackoverflow.com/questions/5665156/calling-awt-frame-methods-from-subclass/5786005#5786005)。 –
在panel1的構造函數中,是否調用jFrame上的.pack()? –
奇怪的是,我發現在實際情況下這實際上更正確。 – mre