cardlayout in java

ww‮itfigi.w‬dea.com

CardLayout is a layout manager in Java that allows you to switch between different panels, as if they were cards in a deck. Only one panel is visible at a time, and you can use buttons or other components to switch between them.

Here's an example of how to use CardLayout to create a simple GUI with two panels:

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

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

        // Create two panels with different contents
        JPanel panel1 = new JPanel();
        panel1.add(new JLabel("This is panel 1."));
        JButton button1 = new JButton("Go to panel 2");
        button1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                CardLayout layout = (CardLayout) cardPanel.getLayout();
                layout.show(cardPanel, "panel2");
            }
        });
        panel1.add(button1);

        JPanel panel2 = new JPanel();
        panel2.add(new JLabel("This is panel 2."));
        JButton button2 = new JButton("Go to panel 1");
        button2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                CardLayout layout = (CardLayout) cardPanel.getLayout();
                layout.show(cardPanel, "panel1");
            }
        });
        panel2.add(button2);

        // Add the panels to the cardPanel
        cardPanel.add(panel1, "panel1");
        cardPanel.add(panel2, "panel2");

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

        // Set the size of the frame and show it
        frame.pack();
        frame.setVisible(true);
    }
}

In this example, we create a JFrame and a JPanel with a CardLayout. We also create two other JPanels with different contents, and add them to the cardPanel using the add method. We use a unique string identifier for each panel, so we can switch between them using the show method of the CardLayout.

We also create two buttons, one on each panel, that allow the user to switch between the panels by calling the show method with the appropriate string identifier. Finally, we add the cardPanel to the JFrame and show it.