这个代码好好背一背,作为一个模板:
package awt1yue16;
import java.awt.*;
import java.awt.event.ActionListener;
public class CardLayoutTest {
Frame f = new Frame("测试窗口");
String[] names = {"第一张","第二张", "第三张", "第四张","第五张"};
Panel p1 = new Panel();
public void init()
{
final CardLayout c = new CardLayout();
p1.setLayout(c);
for(int i = 0; i<names.length;i++)
{
//这个代码要研究一下,作用
p1.add(names[i],new Button(names[i]));
}
Panel p = new Panel();
ActionListener listener = e ->
{
//里面包含一个 switch语句
switch(e.getActionCommand())
{
//如果事件返回"上一张",就执行输出p1容器中的上一张卡片
case "上一张":
c.previous(p1);
break;
case "下一张":
c.next(p1);
break;
case "第一张":
c.first(p1);
break;
case "最后一张":
c.last(p1);
break;
case "第三张":
//这是按照名字取出的卡片
c.show(p1,"第三张");
break;
}
};
Button previous = new Button("上一张");
//把监听功能的对象listener,添加到按钮previous上面,这个按钮就有监听事件的功能
previous.addActionListener(listener);
Button next = new Button("下一张");
next.addActionListener(listener);
Button first = new Button("第一张");
first.addActionListener(listener);
Button last = new Button("最后一张");
last.addActionListener(listener);
Button third = new Button("第三张");
third.addActionListener(listener);
p.add(previous);
p.add(next);
p.add(first);
p.add(last);
p.add(third);
//对容器p和p1进行布局
f.add(p1); //默认布局在中间
f.add(p,BorderLayout.SOUTH);
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
new CardLayoutTest().init();
}
}