很久以前学java写的一个题目,内容仅供参考,转发请附带原地址。
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CardLayoutTest extends JFrame implements ActionListener {
// 卡片布局管理器
private CardLayout cardLayout;
// 使用卡片布局管理器的面板
private JPanel cardpanel;
Button nextButton;
Button preButton;
public CardLayoutTest() {
cardLayout = new CardLayout(10,10);
JPanel cardpanel = new JPanel(cardLayout);
setTitle("CardLayoutTest");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JPanel p4 = new JPanel();
p1.add(new Label("The First Card",Label.CENTER));
p1.setBackground(Color.yellow);
cardpanel.add(p1);
p2.add(new Label("The Second Card",Label.CENTER));
p2.setBackground(Color.green);
cardpanel.add(p2);
p3.add(new Label("The Third Card",Label.CENTER));
p3.setBackground(Color.magenta);
cardpanel.add(p3);
p4.add(new Label("The Fourth Card",Label.CENTER));
p4.setBackground(Color.cyan);
cardpanel.add(p4);
JPanel btn = new JPanel(new GridLayout(1,2));
JButton prebutton = new JButton("上一张");
JButton nextbutton = new JButton("下一张");
btn.add(prebutton);
btn.add(nextbutton);
nextbutton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cardLayout.next(cardpanel);
}
}); // 注册按钮事件监听器
prebutton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cardLayout.previous(cardpanel);
}
}); // 注册按钮事件监听器
this.add(btn, BorderLayout.SOUTH);
// 将使用了CardLayout的面板添加到窗体中显示
this.add(cardpanel, BorderLayout.CENTER);
setVisible(true);
}
public static void main(String[] args) {
new CardLayoutTest();
}
@Override
public void actionPerformed(ActionEvent e) {
}
}
运行界面



