package itheima001; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class cardlayoutDemo { public static void main(String[] args) { Frame frame=new Frame("这里测试cardlayout"); Panel p1=new Panel(); CardLayout cardlayout=new CardLayout(); p1.setLayout(cardlayout); String[] str={"第一张","第二张","第三张","第四张","第五张"}; for(int x=0;x<str.length;x++){ p1.add(str[x],new Button(str[x])); } frame.add(p1); Panel p2=new Panel(); Button b1 = new Button("上一张"); Button b2 = new Button("下一张"); Button b3 = new Button("第一张"); Button b4 = new Button("最后一张"); Button b5 = new Button("第三张"); //创建事件监听器 ActionListener Listener=new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand();//这个字符串是按钮上的文字 switch (actionCommand){ case "上一张": cardlayout.previous(p1); break; case "下一张": cardlayout.next(p1); break; case "第一张": cardlayout.first(p1); break; case "最后一张": cardlayout.last(p1); break; case "第三张": cardlayout.show(p1,"第三张"); break; } } }; b1.addActionListener(Listener); b2.addActionListener(Listener); b3.addActionListener(Listener); b4.addActionListener(Listener); b5.addActionListener(Listener); p2.add(b1); p2.add(b2); p2.add(b3); p2.add(b4); p2.add(b5); frame.add(p2,BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); } }
卡片布局管理器cardlayout和事件监听器Actionlistenner
最新推荐文章于 2024-08-23 15:54:50 发布