1. 程式人生 > >Java中CardLayout布局方式的應用

Java中CardLayout布局方式的應用

rdl pre 賦值 trace import 進行 run方法 swing button

 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 }

Java中CardLayout布局方式的應用