一个简单的CardLayout程序实例,代码如下:
publicclassBWF {
staticjava.awt.CardLayoutcard;
staticJPanelpanel;
staticintwidth=500;
staticintheight=600;
publicstaticvoidmain(String[] args){
JFrame jf=newJFrame();
jf.setSize(width,height);
JPanel contentPane1=newJPanel();
jf.setContentPane(contentPane1);//将中间容器组件对象contentPane设置为内容面板
jf.setLayout(newBorderLayout());
javax.swing.JPanel p =newJPanel();
JButton b1=newJButton("<上一步>");
JButton b2=newJButton("<下一步>");
JButton b1_1=newJButton("1");
JButton b1_2=newJButton("2");
JButton b1_3=newJButton("3");
b1_1.setMargin(newInsets(2,2,2,2));
b1_2.setMargin(newInsets(2,2,2,2));
b1_3.setMargin(newInsets(2,2,2,2));
p.add(b1);
p.add(b1_1);
p.add(b1_2);
p.add(b1_3);
p.add(b2);
JPanel p_1=newJPanel();
JPanel p_2=newJPanel();
JPanel p_3=newJPanel();
p_1.setBackground(Color.RED);
p_2.setBackground(Color.BLUE);
p_3.setBackground(Color.green);
p_1.add(newJLabel("Jpanel_1"));
p_2.add(newJLabel("Jpanel_2"));
p_3.add(newJLabel("Jpanel_3"));
card=newjava.awt.CardLayout(5,5);//创建一个制定水平和垂直间隙的新卡片布局
panel=newJPanel(card);//panel布局管理器设置为卡片布局管理器
panel.setPreferredSize(newDimension(200, 300));
panel.add(p_1,"p1");
panel.add(p_2,"p2");
panel.add(p_3,"p3");
b1.addActionListener(newActionListener() {//上一步动作按钮
publicvoidactionPerformed(ActionEvent e) {
card.previous(panel);
}
});
b2.addActionListener(newActionListener() {//下一步动作按钮
publicvoidactionPerformed(ActionEvent e) {
card.next(panel);
}
});
b1_1.addActionListener(newActionListener() {//直接跳转到p_1
publicvoidactionPerformed(ActionEvent e) {
card.show(panel,"p1");
}
});
b1_2.addActionListener(newActionListener() {//直接跳转到p_2
publicvoidactionPerformed(ActionEvent e) {
card.show(panel,"p2");
}
});
b1_3.addActionListener(newActionListener() {//直接跳转到p_3
publicvoidactionPerformed(ActionEvent e) {
card.show(panel,"p3");
}
});
contentPane.add(panel,BorderLayout.NORTH);
contentPane.add(p,BorderLayout.CENTER);
}
}