Skip to content

CardLayout in Swing

discorddioxin edited this page Mar 31, 2021 · 1 revision

Contents


Documentation


Swapping Components

Create a "deck" panel

JPanel deck = new JPanel();

Create the components to be swapped between, known as "cards"

JButton buttonOne = new JButton("Click 1"); // first card
JButton buttonTwo = new JButton("Click 2"); // second card
JPanel panel = new JPanel(); // third card

Add cards to the deck

deck.add(buttonOne, "first button");
deck.add(buttonTwo, "second button");
deck.add(panel, "panel");

Add a CardLayout to the deck panel

CardLayout layout = new CardLayout();
deck.setLayout(layout);

Use the CardLayout to swap between cards

layout.show(deck, "panel");
Clone this wiki locally