Java Swing Tutorial - Java Swing CardLayout

The CardLayout lays out components as a stack of cards. Only one card at the top is visible in a CardLayout.

CardLayout makes only one component visible at a time.

The following steps shows how to use a CardLayout for a container:

First,create a container such as a JPanel.

JPanel cardPanel = new JPanel();

Then, create a CardLayout object.

CardLayout  cardLayout = new CardLayout();

Then set the layout manager for the container.


After that, add components to the container. we need to give a name to each component.

cardPanel.add(new JButton("Card 1"),  "myCard");

"myCard" can be used in the show() method of the CardLayout to make this card visible.

Finally, call next() method from CardLayout to show the next card.;

The CardLayout class has several methods to go through components.

By default, it shows the first component that was added to it.

All show-related methods take the container as an argument.

The first() and last() methods show the first and the last card, respectively.

The previous() and next() methods show the previous and the next card from the card currently being shown.

If the last card is showing, calling the next() method shows the first card. If the first card is showing, calling the previous() method shows the last card.


The following code demonstrates how to use a CardLayout.

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.Dimension;
// w ww. j  av  a  2 s. c  om
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame("CardLayout");
    Container contentPane = frame.getContentPane();

    JPanel buttonPanel = new JPanel();
    JButton nextButton = new JButton("Next");
    contentPane.add(buttonPanel, BorderLayout.SOUTH);

    final JPanel cardPanel = new JPanel();
    final CardLayout cardLayout = new CardLayout();

    for (int i = 1; i <= 5; i++) {
      JButton card = new JButton("Card " + i);
      card.setPreferredSize(new Dimension(200, 200));
      String cardName = "card" + 1;
      cardPanel.add(card, cardName);
    contentPane.add(cardPanel, BorderLayout.CENTER);
    nextButton.addActionListener(e ->;