learning java AWT 布局管理器CardLayout
import javax.swing.*; import java.awt.*; import java.awt.event.ActionListener; public class CardLayoutTest { Frame f = new Frame("cardlayout test"); Panel p1 = new Panel(); String[] names = {"上一张","下一张","第一张","最后一张","第三张"}; public void init(){ final var c = new CardLayout(); p1.setLayout(c); for(var i = 0; i < names.length; i++){ p1.add(names[i], new JButton(names[i])); } var p = new Panel(); ActionListener listener = e -> { switch (e.getActionCommand()){ case "上一张": System.out.println("previous"); c.previous(p1); break; case "下一张": c.next(p1); System.out.println("next"); break; case "第一张": c.first(p1); System.out.println("first"); break; case "最后一张": c.last(p1); System.out.println("last"); break; case "第三张": c.show(p1, "第三张"); System.out.println("third"); break; } }; var previous = new JButton("上一张"); previous.addActionListener(listener); var next = new JButton("下一张"); next.addActionListener(listener); var first = new JButton("第一张"); first.addActionListener(listener); var last = new JButton("最后一张"); last.addActionListener(listener); var third = new JButton("第三张"); third.addActionListener(listener); p.add(previous); p.add(next); p.add(first); p.add(last); p.add(third); f.add(p1); f.add(p, BorderLayout.NORTH); f.setLocation(100,100); f.setBounds(100,100,300,500); f.pack(); f.setVisible(true); } public static void main(String[] args) { new CardLayoutTest().init(); } }
output: