使用CardLayout布局管理器。
final CardLayout cards = new CardLayout();
final JPanel container = new JPanel(cards);
container.add(panel1, "panel1");
container.add(panel2, "panel2");
button1.addActionListener(new ActionListener(){
@Override public void actionPerformed(ActionEvent e){
cards.show(container, "panel1");
}
});
button2.addActionListener(new ActionListener(){
@Override public void actionPerformed(ActionEvent e){
cards.show(container, "panel2");
}
});
初始化时,把所有panel都设成invisiable. 你在按按钮1时,将panel1的isVisible设成true,把panel2和panel3都设成不可见. 按按钮2时,把panel1和panel3都设成不可见,再把panel2设成可见。同理做按钮3.
完整代码完全是按你要求写的。
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TESTswing extends JPanel implements ActionListener{
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JButton btn1 = new JButton("Button1");
JButton btn2 = new JButton("Button2");
public TESTswing()
{
p1.add(btn1);
p1.add(btn2);
p2.add(new JLabel("I’m is p2"));
p3.add(new JLabel("I’m is p3"));
p2.setVisible(false);
p3.setVisible(false);
this.add(p1);
this.add(p2);
this.add(p3);
btn1.addActionListener(this);
btn2.addActionListener(this);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(200, 200);
Container contentPane = frame.getContentPane();
contentPane.add(new TESTswing());
frame.show();
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String cmd = e.getActionCommand();
if (cmd.equals("Button1"))
{
p2.setVisible(true);
p3.setVisible(false);
}
else
{
p2.setVisible(false);
p3.setVisible(true);
}
}