Using a CardLayout Manager : CardLayout « Swing « Java Tutorial






Using a CardLayout Manager
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TryCardLayout extends JPanel implements ActionListener {
  CardLayout card = new CardLayout(50, 50); // Create layout
  public TryCardLayout() {
    setLayout(card);
    JButton button;
    for (int i = 1; i <= 6; i++) {
      add(button = new JButton(" Press " + i), "Card" + i); // Add a button
      button.addActionListener(this); // Add listener for button
    }
  }
  // Handle button events
  public void actionPerformed(ActionEvent e) {
    card.next(this); // Switch to the next card
  }
  public static void main(String[] args) {
    JFrame aWindow = new JFrame();
    aWindow.setBounds(30, 30, 300, 300);
    aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    aWindow.getContentPane().add(new TryCardLayout());
    aWindow.setVisible(true);
  }
}








14.93.CardLayout
14.93.1.What is the CardLayoutWhat is the CardLayout
14.93.2.CardLayout methods
14.93.3.Using a CardLayout ManagerUsing a CardLayout Manager