用java实现以下功能:(1)利用CardLayout布局管理器完成界面设计,添加三个命令按钮Jbutton,初始显示“第一张卡片”,当单击按钮时显示下一卡片,如下图所示。
时间: 2024-03-01 14:51:45 浏览: 103
以下是Java代码实现该功能的示例:
```java
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CardLayoutDemo extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JPanel panel;
private JButton button1;
private JButton button2;
private JButton button3;
private CardLayout cardLayout;
public CardLayoutDemo() {
setTitle("CardLayout Demo");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
cardLayout = new CardLayout();
panel.setLayout(cardLayout);
JPanel card1 = new JPanel();
card1.add(new JButton("Button 1"));
JPanel card2 = new JPanel();
card2.add(new JButton("Button 2"));
JPanel card3 = new JPanel();
card3.add(new JButton("Button 3"));
panel.add(card1, "card1");
panel.add(card2, "card2");
panel.add(card3, "card3");
button1 = new JButton("第一张卡片");
button2 = new JButton("下一张卡片");
button3 = new JButton("最后一张卡片");
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
Container contentPane = getContentPane();
contentPane.add(panel, "Center");
contentPane.add(button1, "North");
contentPane.add(button2, "South");
contentPane.add(button3, "East");
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1) {
cardLayout.first(panel);
} else if (e.getSource() == button2) {
cardLayout.next(panel);
} else if (e.getSource() == button3) {
cardLayout.last(panel);
}
}
public static void main(String[] args) {
new CardLayoutDemo();
}
}
```
在这个示例中,我们创建了一个JFrame窗口,并在其中使用CardLayout布局管理器来管理三个面板。我们还添加了三个JButton,用于显示第一张卡片、下一张卡片和最后一张卡片。当用户单击其中一个按钮时,我们使用CardLayout的first、next和last方法来切换面板。这样,用户可以通过单击按钮来浏览不同的卡片。
阅读全文