📄 testcardlayout.java
字号:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class testCardLayout extends JFrame implements ActionListener {
Container contentPane;
JPanel jpanel = new JPanel();
CardLayout card = new CardLayout(); //CardLayout对象
JButton jbtn[];
String cards[] = {"第一张卡片", "下一张卡片", "上一张卡片", "最后一张卡片"};
public testCardLayout() {
super("CardLayout");
contentPane = this.getContentPane();
jpanel.setLayout(card); //设置内容格的布局
JPanel card1 = new JPanel(); //定义第一张卡片
JLabel jlabel1 = new JLabel("卡片一"); //上面仅有一个标签
card1.add(jlabel1);
jpanel.add(card1, jlabel1.getText()); //将第一张卡片加入jpanel面板
JPanel card2 = new JPanel(); //定义第2张卡片
JTextField field = new JTextField("卡片二");
card2.add(field);
jpanel.add(card2, field.getText()); //将第二张卡片加入jpanel面板
JPanel card3 = new JPanel(); //定义第三张卡片
JLabel jlabel3 = new JLabel("卡片三");
card3.setLayout(new BorderLayout());
card3.add(new JButton("北"), BorderLayout.NORTH);
card3.add(new JButton("南"), BorderLayout.SOUTH);
card3.add(new JButton("西"), BorderLayout.WEST);
card3.add(new JButton("东"), BorderLayout.EAST);
card3.add(jlabel3, BorderLayout.CENTER);
jpanel.add(card3, jlabel3.getText()); //将第三张卡片加入jpanel面板
JPanel controls = new JPanel(); //创建控制面板
controls.setLayout(new GridLayout(2, 2));
jbtn = new JButton[cards.length];
for (int i = 0; i < cards.length; i++) {
jbtn[i] = new JButton(cards[i]);
jbtn[i].addActionListener(this);
controls.add(jbtn[i]); //将按钮加入controls面板
}
contentPane.add(controls, BorderLayout.WEST);
contentPane.add(jpanel, BorderLayout.EAST);
setSize(350, 200);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() == jbtn[0]) //显示第一张卡片
card.first(jpanel);
else if (evt.getSource() == jbtn[1]) //显示下一张卡片
card.next(jpanel);
else if (evt.getSource() == jbtn[2]) //显示前一张卡片
card.previous(jpanel);
else if (evt.getSource() == jbtn[3]) //显示最后一张卡片
card.last(jpanel);
}
public static void main(String args[]) {
testCardLayout obj = new testCardLayout();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -