Chức năng của CardLayout sắp xếp component theo trình tự và chỉ một component hiển thị tại một thời điểm, mỗi component được coi như một thẻ (card).
CardLayout
- CardLayout khác别其他 layout: các layout khác cố gắng hiển thị tất cả component cùng lúc, CardLayout chỉ hiển thị một component tại một thời điểm.
- Trong CardLayout, các card thường đặt trong container như JPanel. Component được đưa vào hàng đợi card theo thứ tự thêm.
- Phương thức quan trọng: first(), last(), next(), previous(), show().
Ví dụ
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutTest extends JFrame implements ActionListener {
CardLayout card;
JButton b1, b2, b3;
Container con;
CardLayoutTest() {
con = this.getContentPane();
card = new CardLayout(40, 30);
con.setLayout(card);
b1 = new JButton("Java");
b2 = new JButton("Python");
b3 = new JButton("Scala");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
con.add("a", b1);
con.add("b", b2);
con.add("c", b3);
}
public void actionPerformed(ActionEvent e) {
card.next(con);
}
public static void main(String[] args) {
CardLayoutTest clt = new CardLayoutTest();
clt.setTitle("CardLayout Test");
clt.setSize(350, 275);
clt.setLocationRelativeTo(null);
clt.setDefaultCloseOperation(EXIT_ON_CLOSE);
clt.setVisible(true);
}
}
Trong ví dụ trên, dùng CardLayout manager chỉ một component (Java) hiển thị trên cửa sổ. Khi click cửa sổ, các component còn lại (Python và Scala) sẽ hiển thị lần lượt.
Kết quả
