The elements of a CardLayout are stacked, one on top of the other, like a deck of cards.
In Core Java, the elements of a CardLayout
are organized in a stack-like fashion, where only one card is visible at a time. It’s like dealing a deck of cards where only the top card is visible, and you can switch between cards to show a different one.
The CardLayout
class is a layout manager for a container that allows you to display different components (cards) in the same area. You can switch between cards programmatically to show the desired component.
Here is a simple example of using CardLayout
in Java:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class CardLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("CardLayout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
JPanel cardPanel = new JPanel();
CardLayout cardLayout = new CardLayout();
cardPanel.setLayout(cardLayout);
JButton card1Button = new JButton("Card 1");
JButton card2Button = new JButton("Card 2");
card1Button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cardLayout.show(cardPanel, "Card 1");
}
});
card2Button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cardLayout.show(cardPanel, "Card 2");
}
});
cardPanel.add(card1Button, "Card 1");
cardPanel.add(card2Button, "Card 2");
frame.add(cardPanel);
frame.setVisible(true);
}
}
In this example, CardLayout
is used to manage two cards (buttons in this case) in a panel. Clicking the buttons switches between the cards, demonstrating the stack-like behavior of CardLayout
.