// CardLayoutTest.java
package com.jdojo.swing.intro;
import java.awt.Container;
import javax.swing.JFrame;
import java.awt.CardLayout;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.Dimension;
import java.awt.BorderLayout;
public class CardLayoutTest {
public static void main(String[] args) {
JFrame frame = new JFrame("CardLayout Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = frame.getContentPane();
// Add a Next JButton in a JPanel to the content pane
JPanel buttonPanel = new JPanel();
JButton nextButton = new JButton("Next");
buttonPanel.add(nextButton);
contentPane.add(buttonPanel, BorderLayout.SOUTH);
// Create a JPanel and set its layout to CardLayout
final JPanel cardPanel = new JPanel();
final CardLayout cardLayout = new CardLayout();
cardPanel.setLayout(cardLayout);
// Add five JButtons as cards to the cardPanel
for (int i = 1; i <= 5; i++) {
JButton card = new JButton("Card " + i);
card.setPreferredSize(new Dimension(200, 200));
String cardName = "card" + 1;
cardPanel.add(card, cardName);
}
// Add the cardPanel to the content pane
contentPane.add(cardPanel, BorderLayout.CENTER);
// Add an action listener to the Next button
nextButton.addActionListener(e -> cardLayout.next(cardPanel));
frame.pack();
frame.setVisible(true);
}
}
Demonstrates how to use a CardLayout. Shows the resulting JFrame. When you click the Next button, the next card is flipped. The program adds two JPanels to the content pane of the JFrame. One JPanel, buttonPanel, has the Next button, and it is added to the south area of the content pane. Note that, by default, a JPanel uses a FlowLayout
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.