1 /* 2 涉及Panel中的图片的加载,还有Frame的关闭的方法, CardLayout(int hgap, int vgap)就会决定卡片面板的大小 3 匿名类的使用。。。 4 */ 5 import java.awt.*; 6 import java.awt.event.*; 7 import javax.swing.*; 8 public class CardLayoutDemo extends Frame{ 9 Panel pCards=new Panel();//卡片面板 10 CardLayout Clayout=new CardLayout(120, 50);//设置卡片和面板边界的垂直和水平距离 11 public CardLayoutDemo(){ 12 setLayout(new BorderLayout(100, 20)); 13 Panel pBtn = new Panel();//按钮面板 14 15 pCards.setLayout(Clayout); 16 //pCards.setPreferredSize(new Dimension(30,40));//这句不再起作用了:因为其父类CardLayoutDemo使用的是BorderLayout布局方式,会自动填充 17 pCards.setBackground(Color.red); 18 pBtn.setBackground(Color.yellow); 19 pBtn.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10)); 20 pBtn.setPreferredSize(new Dimension(200, 50)); 21 22 Button tmpB; 23 pBtn.add(tmpB = new Button("第一张")); 24 tmpB.addActionListener(new myActionListener()); 25 tmpB.setActionCommand("first"); 26 pBtn.add(tmpB = new Button("下一张")); 27 tmpB.addActionListener(new myActionListener()); 28 tmpB.setActionCommand("next"); 29 30 pBtn.add(tmpB = new Button("前一张")); 31 tmpB.addActionListener(new myActionListener()); 32 tmpB.setActionCommand("previous"); 33 34 pBtn.add(tmpB = new Button("最后一张")); 35 tmpB.addActionListener(new myActionListener()); 36 tmpB.setActionCommand("last"); 37 38 39 for(int i=1; i<=4; ++i){ 40 myPanel tmpP; 41 pCards.add(""+i, tmpP=new myPanel(i){ 42 public void paint(Graphics g){ 43 g.drawImage(new ImageIcon("zjy"+i+".jpg").getImage(), 20, 0, 300, 400, this); 44 } 45 }); 46 tmpP.setBackground(Color.blue); 47 //tmpP.setSize(new Dimension(300, 400));//tmpP接受了匿名类对象,可以通过这种方法更改匿名类的属性 48 //这里不设置的原因是它的大小由CardLayout(int hgap, int vgap)决定了 49 } 50 add(pBtn, "North"); 51 add(pCards, "Center"); 52 } 53 class myActionListener implements ActionListener{ 54 public void actionPerformed(ActionEvent e){ 55 String str=e.getActionCommand(); 56 if(str.equals("first")) 57 Clayout.first(pCards); 58 else if(str.equals("next")) 59 Clayout.next(pCards); 60 else if(str.equals("previous")) 61 Clayout.previous(pCards); 62 else if(str.equals("last")) 63 Clayout.last(pCards); 64 } 65 } 66 67 public static void main(String args[]){ 68 CardLayoutDemo myWindow = new CardLayoutDemo(); 69 myWindow.setSize(new Dimension(600, 600)); 70 myWindow.setResizable(false); 71 myWindow.addWindowListener(new myClosingListener()); 72 myWindow.setVisible(true); 73 } 74 } 75 76 77 class myClosingListener extends WindowAdapter{ 78 public void windowClosing(WindowEvent e){ 79 System.exit(0); 80 } 81 } 82 83 class myPanel extends Panel{ 84 int i; 85 public myPanel(int i){ 86 this.i=i; 87 } 88 }
CardLayout布局练习(小的图片浏览器),布布扣,bubuko.com
原文:http://www.cnblogs.com/hujunzheng/p/3811123.html