Java Swing How to - Show different cards in a CardLayout








Question

We would like to know how to show different cards in a CardLayout.

Answer

import java.awt.BorderLayout;
import java.awt.CardLayout;
/*ww  w .  ja v a 2 s . c  om*/
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main extends JFrame {
  JPanel cardPanel = new JPanel(), jp1 = new JPanel(), jp2 = new JPanel(),
      buttonPanel = new JPanel();
  JLabel jl1 = new JLabel("Card 1"), jl2 = new JLabel("Card 2");
  JButton btn1 = new JButton("Show Card 1"), btn2 = new JButton("Show Card 2");
  CardLayout cardLayout = new CardLayout();

  public Main() {
    setSize(400, 300);
    cardPanel.setLayout(cardLayout);
    jp1.add(jl1);
    jp2.add(jl2);
    cardPanel.add(jp1, "1");
    cardPanel.add(jp2, "2");

    btn1.addActionListener(e -> cardLayout.show(cardPanel, "1"));
    btn2.addActionListener(e -> cardLayout.show(cardPanel, "2"));
    buttonPanel.add(btn1);
    buttonPanel.add(btn2);
    add(cardPanel, BorderLayout.NORTH);
    add(buttonPanel, BorderLayout.SOUTH);
  }

  public static void main(String[] args) {
    Main frame = new Main();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }
}