eg:
package com.chengzhi.pkg1;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestGui extends JFrame implements ActionListener{
JPanel p1, p2, p3;
JButton b1, b2;
CardLayout cardlayout;
public TestGui(){
p1 = new JPanel();
p2 = new JPanel();
p3 = new JPanel();
b1 = new JButton("显示红色按钮");
b2 = new JButton("显示绿色按钮");
cardlayout = new CardLayout();
p1.setLayout(cardlayout);
p2.setBackground(Color.red);
p3.setBackground(Color.green);
p1.add("panel2", p2);
p1.add("panel3", p3);
p2.add(b2);
p3.add(b1);
this.getContentPane().add(p1);
this.setSize(300, 300);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//cardlayout.last(p1);
//cardlayout.first(p1);
//cardlayout.show(p1, "panel2");
b1.addActionListener(this);
b2.addActionListener(this);
}
public static void main(String[] args) {
new TestGui();
}
@Override
public void actionPerformed(ActionEvent e) {
JButton b = (JButton)e.getSource();
if (b == b1){
//cardlayout.show(p1, "panel2");
cardlayout.next(p1);
}
if (b == b2)
{
//cardlayout.show(p1, "panel3");
cardlayout.next(p1);
}
}
}原文地址:http://blog.csdn.net/qq_22075977/article/details/45934225