How to switch between cards in CardLayout on a Swing Screen?

Jul 21, 2025

Leave a message

Isabella Hernandez
Isabella Hernandez
Isabella is a financial analyst at Xinxiang Lanhai Environmental Technology Co., Ltd. She is responsible for analyzing the company's financial situation, providing financial support and strategic advice for the company's development.

How to Switch Between Cards in CardLayout on a Swing Screen

As a trusted Swing Screen supplier, I often encounter customers who are interested in optimizing the user experience of their Swing applications. One common requirement is the ability to switch between different views or "cards" within a single container. This is where the CardLayout class in Java Swing comes in handy. In this blog post, I'll walk you through the process of using CardLayout to switch between cards on a Swing screen, providing practical examples and tips along the way.

Understanding CardLayout

CardLayout is a layout manager in Java Swing that allows you to manage multiple components (cards) within a single container. Only one card is visible at a time, and you can switch between cards using various methods provided by the CardLayout class. This is useful for creating wizards, tabbed interfaces, or any application where you need to display different views based on user actions.

To use CardLayout, you first need to create an instance of it and set it as the layout manager for a container, typically a JPanel. Here's a simple example:

import javax.swing.*;
import java.awt.*;

public class CardLayoutExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("CardLayout Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Create a JPanel with CardLayout
        JPanel cardPanel = new JPanel(new CardLayout());

        // Create some cards (JPanels)
        JPanel card1 = new JPanel();
        card1.add(new JLabel("This is Card 1"));

        JPanel card2 = new JPanel();
        card2.add(new JLabel("This is Card 2"));

        // Add the cards to the cardPanel with a name
        cardPanel.add(card1, "card1");
        cardPanel.add(card2, "card2");

        // Add the cardPanel to the frame
        frame.add(cardPanel);

        frame.pack();
        frame.setVisible(true);
    }
}

In this example, we create a JFrame and a JPanel with CardLayout. We then create two cards (JPanels) and add them to the cardPanel with a unique name. Finally, we add the cardPanel to the frame and make it visible. By default, the first card added to the container will be visible.

Switching Between Cards

Now that we have a basic understanding of CardLayout, let's look at how to switch between cards. The CardLayout class provides several methods for this purpose:

  • first(Container parent): Shows the first card in the container.
  • last(Container parent): Shows the last card in the container.
  • next(Container parent): Shows the next card in the container. If the current card is the last one, it wraps around to the first card.
  • previous(Container parent): Shows the previous card in the container. If the current card is the first one, it wraps around to the last card.
  • show(Container parent, String name): Shows the card with the specified name.

Let's modify our previous example to include buttons for switching between cards:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class CardLayoutExampleWithButtons {
    public static void main(String[] args) {
        JFrame frame = new JFrame("CardLayout Example with Buttons");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Create a JPanel with CardLayout
        JPanel cardPanel = new JPanel(new CardLayout());

        // Create some cards (JPanels)
        JPanel card1 = new JPanel();
        card1.add(new JLabel("This is Card 1"));

        JPanel card2 = new JPanel();
        card2.add(new JLabel("This is Card 2"));

        // Add the cards to the cardPanel with a name
        cardPanel.add(card1, "card1");
        cardPanel.add(card2, "card2");

        // Create buttons for switching cards
        JButton nextButton = new JButton("Next");
        JButton prevButton = new JButton("Previous");

        // Get the CardLayout instance
        final CardLayout cardLayout = (CardLayout) cardPanel.getLayout();

        // Add action listeners to the buttons
        nextButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cardLayout.next(cardPanel);
            }
        });

        prevButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cardLayout.previous(cardPanel);
            }
        });

        // Create a panel for the buttons
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(prevButton);
        buttonPanel.add(nextButton);

        // Add the cardPanel and buttonPanel to the frame
        frame.add(cardPanel, BorderLayout.CENTER);
        frame.add(buttonPanel, BorderLayout.SOUTH);

        frame.pack();
        frame.setVisible(true);
    }
}

In this example, we create two buttons for switching between cards: "Next" and "Previous". We then get the CardLayout instance from the cardPanel and add action listeners to the buttons. When the "Next" button is clicked, the next method of the CardLayout is called to show the next card. Similarly, when the "Previous" button is clicked, the previous method is called to show the previous card.

Practical Applications

The ability to switch between cards using CardLayout has many practical applications in Swing applications. Here are a few examples:

  • Wizards: Wizards are a common UI pattern used to guide users through a multi-step process. You can use CardLayout to display different steps of the wizard as separate cards, allowing users to navigate forward and backward easily.
  • Tabbed Interfaces: Tabbed interfaces are another popular UI pattern where users can switch between different views or pages. You can use CardLayout to implement a simple tabbed interface by showing different cards based on the user's tab selection.
  • Dynamic Content: CardLayout can also be used to display dynamic content based on user actions or events. For example, you can show different cards depending on the user's input or the state of the application.

Related Equipment in the Pulp and Paper Industry

In addition to our expertise in Swing Screen technology, we also offer a range of high-quality equipment for the pulp and paper industry. Here are some of our products:

inside details of Screw DigesterScrew Digester

  • Screw Digester: A screw digester is a key piece of equipment in the pulp and paper industry used for cooking wood chips to produce pulp. Our screw digesters are designed for high efficiency and reliability.
  • Belt Conveyor Pulp and Paper: Belt conveyors are used to transport pulp and paper products within a manufacturing facility. Our belt conveyors are built to withstand the harsh conditions of the pulp and paper industry.
  • Shaftless Screw Conveyor: Shaftless screw conveyors are ideal for handling sticky or fibrous materials, such as pulp. Our shaftless screw conveyors are designed for easy maintenance and long service life.

Conclusion

In conclusion, CardLayout is a powerful layout manager in Java Swing that allows you to switch between different views or cards within a single container. By using CardLayout, you can create more dynamic and user-friendly Swing applications. Whether you're building a wizard, a tabbed interface, or any other application that requires switching between views, CardLayout is a great choice.

If you're interested in learning more about our Swing Screen products or our equipment for the pulp and paper industry, please don't hesitate to contact us for a procurement discussion. We're committed to providing high-quality products and excellent customer service.

References

  • "The Java Tutorials: Using CardLayout." Oracle, https://docs.oracle.com/javase/tutorial/uiswing/layout/card.html.
  • "Java Swing: A Beginner's Guide." Herbert Schildt, McGraw-Hill Education, 2014.
Send Inquiry
Contact us if have any question

You can either contact us via phone, email or online form below. Our specialist will contact you back shortly.

Contact now!