import javax.swing.*;import java.awt.*;
import java.awt.event.*;public class Card extends JFrame{/** JFrame的布局管理器是BorderLayout*/JPanel p;//位于中心区域的面板JButton b1,b2,b3,b4;//位于南部区域的四个按钮
JLabel l1,l2,l3,l4;CardLayout c;//设置面板p的布局
Card(String name){super(name);this.setVisible(true);this.setBounds(400,300,400,400);p = new JPanel();//实例化pc = new CardLayout();//实例化cp.setLayout(c);//设置面板p的布局为c,等价于p = new JPanel(c);//实例化4个按钮和标签b1 = new JButton("previous");b2 = new JButton("two");b3 = new JButton("three");b4 = new JButton("next");l1 = new JLabel("first card");l2 = new JLabel("second card");l3 = new JLabel("thirth card");l4 = new JLabel("fourth card");//实例化4个子面板并设定相应背景颜色JPanel p1 = new JPanel();JPanel p2 = new JPanel();JPanel p3 = new JPanel();JPanel p4 = new JPanel(); p1.setBackground(Color.green);p2.setBackground(Color.pink);p3.setBackground(Color.orange);p4.setBackground(Color.lightGray);//把上面4个面板添加到中心面板p中,并把4个面板分别用编号为1,2,3,4代替p.add(p1,"1");p.add(p2,"2");p.add(p3,"3");p.add(p4,"4");//把4个标签分别添加到4个子面板中
p1.add(l1);p2.add(l2);p3.add(l3);p4.add(l4);//实例化位于南部区域的面板,并添加4个按钮JPanel psourth = new JPanel();psourth.add(b1);psourth.add(b2);psourth.add(b3);psourth.add(b4);//把p,psourth分别添加到本JFrame的中心区域和南部区域this.add(p);//等价于this.add(p,BorderLayout.CENTER); 因为默认是把组件添加到中部 this.add(psourth,BorderLayout.SOUTH);//为按钮b1添加监听器,当被按下时显示面板p中的前一个子面板b1.addActionListener(new ActionListener(){@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubc.previous(p);//显示p中的上一个面板
} });//为按钮b2添加监听器,当被按下时显示面板p中的第2个子面板b2.addActionListener(new ActionListener(){@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubc.show(p, "2");//显示p中代号为2的面板
} });//以下类推b3.addActionListener(new ActionListener(){@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubc.show(p, "3");} });b4.addActionListener(new ActionListener(){@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stub
c.next(p);} });//使用匿名内部类为本Frame添加监听器,当点击关闭按钮时结束程序this.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}public static void main(String[] args) {// TODO Auto-generated method stubnew Card("My Card");}}
运行结果: