• How to use Card Layout in Java

    Previously, we talked about the Flow Layout, Border Layout, Grid Layout. Now we will talk about Card Layout in Java which is primarily used in switching between panels. JPanels are stored in a stack (like stack of cards) and only one panel is visible at a time. The others are hidden. Lets take an example for a better understanding.

    Card Layout in Java Example

    package com.javapointers.javase;
    import java.awt.CardLayout;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class CardLayoutTest implements ActionListener {
        JFrame frame;
        JPanel pane1, pane2, pane3, cardPane;
        CardLayout card;
        public CardLayoutTest() {
            frame = new JFrame("CardLayout Test");
            frame.setSize(500, 400);
            pane1 = new JPanel();
            pane2 = new JPanel();
            pane3 = new JPanel();
            cardPane = new JPanel();
            JButton button1 = new JButton("Click me to change panel");
            JButton button2 = new JButton("Click me to change panel");
            JButton button3 = new JButton("Click me to change panel");
            card = new CardLayout();
            cardPane.add(pane1, "First Pane");
            cardPane.add(pane2, "Second Pane");
            cardPane.add(pane3, "Third Pane");
        public void actionPerformed(ActionEvent e) {
        public static void main(String args[]) {
            CardLayoutTest test = new CardLayoutTest();

    If we run our program, the output will be like below that will show the next panel when we click the button.

    car layout java


    1. cardPane = new JPanel();

      – We need to create an instance of JPanel. This panel will be the one holding other panels.

    2. card = new CardLayout();

      – Create new instance of card layout and store it in variable card.

    3. cardPane.setLayout(card);

      – Sets the layout of our cardPane (the one we created earlier) to card layout.

    4. cardPane.add(pane1, "First Pane");
      cardPane.add(pane2, "Second Pane");
      cardPane.add(pane3, "Third Pane");

      – Add our panels to the cardPane. Our cardPane now holds different panels. When adding a component, each component should have corresponding String text like for example, our pane1 has a corresponding text of “First Pane”.

    5. card.next(cardPane);

      – This method has been called inside the actionPerformed method. This means that when the user click the button, the cardPane will then hide the current panel and show the next panel. In our example, the cardPane will hide the black panel and show the blue, and will hide the blue and show the green and so on.

    Next in our tutorial is the Grid Bag Layout Manager which is a more dynamic type of layout managers.

    Related Post