import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Demo2 {
public static void main(String[] args) {
new MyWindow("CardLayout的使用");
}
}
class MyWindow extends JFrame{
JPanel p,p1,p2,p3,pBtn;
JButton preBtn,nextBtn,btn1,btn2,btn3;
CardLayout card;
public MyWindow(String title){
super(title);
this.setSize(500,400);
this.setLocationRelativeTo(null);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
init();
}
private void init() {
p=new JPanel();
p1=new JPanel();
p1.setBackground(Color.red);
p2=new JPanel();
p2.setBackground(Color.green);
p3=new JPanel();
p3.setBackground(Color.yellow);
card=new CardLayout();
p.setLayout(card);
p.add("p1",p1);
p.add("p2",p2);
p.add("p3",p3);
this.add(p,BorderLayout.CENTER);
pBtn=new JPanel();
preBtn=new JButton("<<上一个");
preBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
card.previous(p);
}
});
nextBtn=new JButton("下一个>>");
nextBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
card.next(p);
}
});
btn1=new JButton("1");
btn1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
card.show(p,"p1");
}
});
btn2=new JButton("2");
btn2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
card.show(p,"p2");
}
});
btn3=new JButton("3");
btn3.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
card.show(p,"p3");
}
});
pBtn.add(preBtn);pBtn.add(btn1);pBtn.add(btn2);pBtn.add(btn3);pBtn.add(nextBtn);
this.add(pBtn,BorderLayout.SOUTH);
this.validate();
}