Use CardLayout in Java
Description
The following code shows how to use CardLayout.
CardLayout places components like a deck of cards. Only the "top" component is visible at any one time.
Example
/*from www .j av a2 s . c o m*/
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame {
protected CardLayout layout;
public static void main(String[] args) {
Main ct = new Main();
ct.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ct.displayTab("Green Tab");
ct.setSize(400, 300);
ct.setVisible(true);
}
public Main() {
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);
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »