CardLayout卡片布局(切换到指定卡片演示)
时间: 2024-01-09 14:05:30 浏览: 35
好的,这里是一个简单的 CardLayout 卡片布局的示例代码,包含了切换到指定卡片的演示。请运行代码并尝试点击按钮切换卡片。
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutDemo implements ActionListener {
JPanel cards; // 卡片面板
final static String BUTTONPANEL = "按钮面板";
final static String TEXTPANEL = "文本面板";
public void addComponentToPane(Container pane) {
// 创建按钮面板
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.white);
JButton btn1 = new JButton("切换到文本面板");
btn1.addActionListener(this);
buttonPanel.add(btn1);
// 创建文本面板
JPanel textPanel = new JPanel();
textPanel.setBackground(Color.lightGray);
JLabel label = new JLabel("这是文本面板");
textPanel.add(label);
// 创建卡片面板
cards = new JPanel(new CardLayout());
cards.add(buttonPanel, BUTTONPANEL);
cards.add(textPanel, TEXTPANEL);
// 将卡片面板添加到容器中
pane.add(cards, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e) {
CardLayout cl = (CardLayout) (cards.getLayout());
cl.show(cards, TEXTPANEL); // 切换到文本面板
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("CardLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建并设置面板
CardLayoutDemo demo = new CardLayoutDemo();
demo.addComponentToPane(frame.getContentPane());
// 显示窗口
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
```
在这个示例中,我们创建了一个 `JPanel` 作为卡片面板,并且使用 `CardLayout` 布局管理器将按钮面板和文本面板添加到卡片面板中。
通过使用 `CardLayout` 的 `show()` 方法,我们可以根据卡片的名字来切换卡片。在 `actionPerformed()` 方法中,我们使用 `show()` 方法将卡片面板切换到名为 `TEXTPANEL` 的卡片。
希望这个示例能够帮助你了解如何使用 CardLayout 卡片布局。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![chm](https://img-home.csdnimg.cn/images/20210720083646.png)
![CHM](https://img-home.csdnimg.cn/images/20210720083646.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)