【发布时间】:2011-07-01 11:28:38
【问题描述】:
我有一个程序,其中有一个 JFrame 和一个 JButton。当用户点击JButton时,JFrame中的所有Components都会被移除,并添加一个红色背景的JPanel。
当我单击JButton 时,红色的JPanel 不会变得可见,除非我调整JFrame 的大小(我使用的是Windows 7)。有没有办法实现我想要的,而无需手动调整 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. */
}
}
【问题讨论】:
-
在 panel1 构造函数中,你是在 jFrame 上调用 .pack() 吗?
-
奇怪的是,我发现考虑到具体情况,这实际上更正确。
-
考虑使用
CardLayout。见E.G.。
标签: java swing jframe jpanel resize