- Place components like a deck of cards.
- Only the "top" component is visible at any one time.
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CardLayoutBehaviour extends JFrame {
protected CardLayout layout;
public static void main(String[] args) {
CardLayoutBehaviour ct = new CardLayoutBehaviour();
ct.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ct.displayTab("Green Tab");
ct.setSize(400, 300);
ct.setVisible(true);
}
public CardLayoutBehaviour() {
JPanel tab;
Container pane = getContentPane();
layout = new CardLayout();
pane.setLayout(layout);
tab = new JPanel();
tab.setBackground(Color.red);
pane.add(tab, "Red Tab");
tab = new JPanel();
tab.setBackground(Color.green);
pane.add(tab, "Green Tab");
tab = new JPanel();
tab.setBackground(Color.blue);
pane.add(tab, "Blue Tab");
}
public void displayTab(String name) {
layout.show(this.getContentPane(), name);
}
}