Java中CardLayout布局方式的应用


 1 import java.awt.CardLayout;
 2 import java.awt.Color;
 3 import java.awt.Container;
 4 
 5 import javax.swing.JButton;
 6 import javax.swing.JFrame;
 7 
 8 public class CardLayoutDemo {
 9     public static void main(String[] args) {
10         //新建一个JFrame框架
11         JFrame frame = new JFrame("CardLayout");
12         frame.setSize(600, 400);
13         frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
14         
15         final Container cp = frame.getContentPane();//得到一个内容面板;final标记的为常量,只能赋值一次
16         final CardLayout cardlayout = new CardLayout();//因为后期会对layout进行操作,才将其单独定义出来
17         cp.setLayout(cardlayout);//cp.setLayout(new CardLayout())的方式不可行,会出现异常
18         Color[] colors = { Color.white, Color.GRAY, Color.PINK, Color.cyan };
19 
20         for (int i = 0; i < colors.length; i++) {
21             String name = "card" + String.valueOf(i + 1);
22             JButton button = new JButton(name);
23             button.setBackground(colors[i]);
24             cp.add(name, button);
25         }
26 
27         frame.setVisible(true);
28         /**
29          * 要点是创建线程时,要重写Thread类中的run方法
30          */
31         Thread thread = new Thread() {
32             public void run() {
33                 while (true) {
34                     try {
35                         Thread.sleep(400);
36                     } catch (InterruptedException e) {
37                         e.printStackTrace();
38                     }
39                     /**
40                      * cardLayout的next是另外一个内容面板
41                      */
42                     cardlayout.next(cp);
43                 }
44             }
45         };
46         thread.start();//启动线程
47     }
48 }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM