What is CardLayout - Java Swing

Java examples for Swing:CardLayout

Introduction

CardLayout lays out components as a stack of cards.

Only the component at the top is visible in a CardLayout.

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

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

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

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

Demo Code

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.Dimension;

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 Test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();

    JPanel buttonPanel = new JPanel();
    JButton nextButton = new JButton("Next");
    buttonPanel.add(nextButton);//from   w  w w . j a  va2  s  . com
    contentPane.add(buttonPanel, BorderLayout.SOUTH);

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

    for (int i = 1; i <= 10; 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 -> cardLayout.next(cardPanel));

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

Related Tutorials