CardLayout
时间: 2023-08-30 09:12:13 浏览: 63
CardLayout是Java Swing中的一个布局管理器,它可以用于在同一个容器中切换多个组件。CardLayout中的每个组件都被称为一张卡片(card),每次只有一张卡片处于显示状态,其余卡片被隐藏。通过调用CardLayout中的方法,可以在这些卡片之间进行切换。
以下是使用CardLayout的示例代码:
```
import java.awt.CardLayout;
import javax.swing.*;
public class CardLayoutDemo extends JFrame {
private JPanel cards;
private JButton prevButton, nextButton;
public CardLayoutDemo() {
setTitle("CardLayout Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
// 创建卡片面板
cards = new JPanel(new CardLayout());
// 添加多个卡片
cards.add(new JLabel("Card 1"), "card1");
cards.add(new JLabel("Card 2"), "card2");
cards.add(new JLabel("Card 3"), "card3");
// 创建按钮
prevButton = new JButton("Previous");
nextButton = new JButton("Next");
// 添加按钮的事件监听器
prevButton.addActionListener(e -> {
CardLayout cardLayout = (CardLayout) cards.getLayout();
cardLayout.previous(cards);
});
nextButton.addActionListener(e -> {
CardLayout cardLayout = (CardLayout) cards.getLayout();
cardLayout.next(cards);
});
// 将卡片面板和按钮添加到窗口中
add(cards);
add(prevButton, "South");
add(nextButton, "North");
setVisible(true);
}
public static void main(String[] args) {
new CardLayoutDemo();
}
}
```
在上面的示例代码中,我们创建了一个包含三个卡片的面板,并且添加了两个切换卡片的按钮。当用户点击“Previous”按钮时,会显示上一张卡片;当用户点击“Next”按钮时,会显示下一张卡片。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)