Java Swing How to - Switch Component with CardLayout








Question

We would like to know how to switch Component with CardLayout.

Answer

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
/*  ww  w.  j  a  v a2s  .  co m*/
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;

public class Main {
  JPanel mainPanel = new JPanel();
  JMenu menu = new JMenu("Menu");
  JMenuBar menuBar = new JMenuBar();
  CardLayout cardlayout = new CardLayout();

  public Main() {
    mainPanel.setLayout(cardlayout);
    mainPanel.setBackground(Color.white);
    addCard("A");
    addCard("B");
    addCard("C");
    addCard("D");
    menuBar.add(menu);
  }

  private void addCard(String name) {
    JLabel label = new JLabel(name);
    mainPanel.add(label, name);
    menu.add(new JMenuItem(new MenuAction(name)));
  }

  public JComponent getMainPanel() {
    return mainPanel;
  }

  public JMenuBar getMenuBar() {
    return menuBar;
  }

  class MenuAction extends AbstractAction {
    public MenuAction(String name) {
      super(name);
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
      String name = getValue(NAME).toString();
      cardlayout.show(mainPanel, name);
    }
  }

  public static void main(String[] args) {
    Main swapper = new Main();
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(swapper.getMainPanel());
    frame.setJMenuBar(swapper.getMenuBar());
    frame.pack();
    frame.setLocationByPlatform(true);
    frame.setVisible(true);
  }
}