• 沒有找到結果。

10Swing元件與應用.pdf

N/A
N/A
Protected

Academic year: 2021

Share "10Swing元件與應用.pdf"

Copied!
46
0
0

加載中.... (立即查看全文)

全文

(1)Swing 元件與應用 王元俊 Wang Yuan-Jiun [email protected] 1.

(2) 學習目標 • 認識 Swing • 最常用的控制元件 (Swing Controls) – Label – Button – Text Field • 圖檔應用 • 計時器 (Timer) • Scroll Pane 與 Text Area • 檔案讀取與寫入. 2.

(3) 3.

(4) 4.

(5) 認識 Swing • Swing 是一個為 Java 設計的圖形化使用者介面 (GUI) 類別庫。 – GUI: Graphical User Interface • Swing 是 Java 基礎類別 (Java Foundation Classes, JFC) 的一部分。 – JFC 是一個圖形框架 (Graphical Framework), 依據此框架可建構出具有移攜性 (Portable) 的 Java 式圖形式使用者介面。 – JFC 主要是由 Abstract Window Toolkit (AWT)、Swing 以及 Java 2D 三者所構成。 使得 Java 開發的使用者介面,在轉移到各 種作業平台上,都能保有一致性的圖像呈現。 5.

(6) NetBeans 與 Swing. 6.

(7) 範例:JLabel 元件 icon 屬性顯示圖片 • 專案名稱:ShowImage • 視窗元件配置:. • 功能:本範例有三張圖片,使用者按下圖片時, 循環更換圖片。 7.

(8) ShowImage 操作步驟 (1) 1. 在視窗 (JFrame) 中放一個標籤 (JLabel) 元件 jLabel1。 2. 設定 jLabel1 的屬性如下:  text 設定為空字串(也就是清除 text 屬性的 內容)。  preferredSize 設定 Width 為 88,Height 為 75。  toolTipText 設定為「滑鼠點選圖片,可以 更換圖片。」. 8.

(9) ShowImage 操作步驟 (2)  icon 設定圖片 h1.gif。操作步驟如下: A. (建立存放圖片的目錄images)點選 Projects 視窗中 Source Packages,按右鍵, 選取 New → Other… → Categories 選取 Other,File Types 選取 Folder,按 Next。 File Name 輸入 images,按 Finish。 B. (Import圖片到專案目錄)點選 icon 屬性, 開啟如下的視窗。點選「Import to Project…」,選取圖片,將圖片存放在目錄 images 中。 C. 選取h1.gif。. 9.

(10) ShowImage 操作步驟 (3). 10.

(11) ShowImage 操作步驟 (4) 3. 新增一個實例變數 n,用以記錄目前顯示的圖 片號碼。程式碼: private int n = 1;. 4. 點選 jLabel1,點選 Properties 視窗中的 Events, 選取事件 mouseClicked。 5. 觸發事件 jLabel1MouseClicked 的程式如下: private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) { n++; if (n == 4) n = 1; jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource( "/images/h" + String.valueOf(n) + ".gif"))); } 11.

(12) ShowImage 執行結果. 12.

(13) 練習 1. 製作一個猜拳遊戲。畫面上左邊圖片是電腦 出拳,右邊圖片是玩家出拳。玩家利用滑鼠 點選圖片以更換圖片出拳,按下按鈕「出 拳」,電腦隨機出拳,以圖片顯示輸贏結果。 參考畫面如右。. 13.

(14) 範例:圖片瀏覽器 • 專案名稱:ImageIconArray • 說明:利用 ImageIcon 建立圖片陣列,建立字 串陣列,操作陣列索引值,循環顯示圖片與字 串內容。 • 視窗元件配置:. 14.

(15) 圖片瀏覽器功能 • 功能: – 視窗中有三個標籤,分別顯示圖片、中文名 稱、英文名稱。 – 兩個按鈕,按下後會更換圖片與中、英文名 稱。 – 應用 ImageIcon 陣列儲存圖片,中、英文名 稱則使用字串陣列儲存。 – 設定一個實例變數 n,用以記錄目前顯示圖 片與字串在陣列的索引值。. 15.

(16) ImageIconArray 製作步驟 (1) 1. 視窗 (JFrame) 設定 preferredSize,Width 為 700,Height 為 550;title 設定為「圖片瀏覽 器」。 2. 在視窗 (JFrame) 中放一個標籤 (JLabel) 元件 jLabel1。 3. 設定 jLabel1 的屬性如下:  text 設定為空字串(也就是清除 text 屬性的 內容)。  preferredSize 設定 Width 為 432,Height 為 288。  icon 設定圖片 apple.jpg。 16.

(17) ImageIconArray 製作步驟 (2) 4. 新增兩個按鈕,jButton1(前一張), jButton2(下一張)。 5. 新增兩個標籤,jLabel2(顯示英文名稱), jLable3(顯示中文名稱)。 6. 新增 ImageIcon 陣列 myImages,可存放 5 張 圖片。程式碼: private javax.swing.ImageIcon [] myImages = new javax.swing.ImageIcon[5]; 說明:程式碼最前面加上「import javax.swing.ImageIcon;」 敘述,這樣的話程式碼可以簡化為. private ImageIcon [] myImages = new ImageIcon[5]; 17.

(18) ImageIconArray 製作步驟 (3) 7. 新增一個實例變數 n,用以記錄目前顯示圖片 與字串在陣列的索引值。程式碼: private int n = 0;. 8. 新增圖片的中文檔案名稱陣列 chineseName, 程式碼: private String [] chineseName = {"蘋果", "柳橙", "草莓", "甜椒", "番茄"};. 9. 新增圖片的英文檔案名稱陣列 englishName, 程式碼: private String [] englishName = {"Apple", "Orange", "Strawberry", "Sweet-Pepper", "Tomato"}; 18.

(19) ImageIconArray 製作步驟 (4) 10. 在建構函數 (constructor) 中(此範例中,類別 名稱為 NewJFrame)載入圖片檔案到 ImageIcon 陣列。程式碼: public NewJFrame() { initComponents(); myImages[0] = new ImageIcon(getClass().getResource("/images/apple.jpg")); myImages[1] = new ImageIcon(getClass().getResource("/images/orange.jpg")); myImages[2] = new ImageIcon(getClass().getResource("/images/strawberry.jpg")); myImages[3] = new ImageIcon(getClass().getResource("/images/sweetpepper.jpg")); myImages[4] = new ImageIcon(getClass().getResource("/images/tomato.jpg")); }. 19.

(20) ImageIconArray 製作步驟 (5) 11. 下一張按鈕觸發事件 jButton2ActionPerformed 的程式如下: private void jButton2ActionPerformed(java.awt.event.MouseEvent evt) { n = ++n % 5; jLabel1.setIcon(myImages[n]); jLabel2.setText(chineseName[n]); jLabel3.setText(englishName[n]); }. 20.

(21) ImageIconArray 製作步驟 (6) 12. 前一張按鈕觸發事件 jButton1ActionPerformed 的程式如下: private void jButton1ActionPerformed(java.awt.event.MouseEvent evt) { n += 4; n = n % 5; jLabel1.setIcon(myImages[n]); jLabel2.setText(chineseName[n]); jLabel3.setText(englishName[n]); }. 21.

(22) 練習 2. 增加五個預覽小圖片,點選預覽小圖片時, 顯示大圖片與圖片的中、英文名稱。 參考畫面如下:. 22.

(23) 計時器物件 1. 設定執行時間 2. 撰寫計時器執行時回應的程式碼 3. 啟動計時器 timer – timer.start(); 4. 停止計時器 timer – timer.stop();. 23.

(24) 範例:計時器倒數計時 • 範例:CountDown • 視窗畫面. 24.

(25) 計時器倒數計時功能 1. 在文字欄輸入倒數時間,右邊標籤同時顯示輸入值。 2. 按鈕原本顯示「開始」,按下後開始倒數,按鈕顯示 為「暫停」,開始倒數。倒數的數字顯示在右邊標籤。 3. 按鈕顯示「暫停」時,按下後暫停倒數,按鈕顯示為 「繼續」。 4. 按鈕顯示「繼續」時,按下後繼續倒數,按鈕顯示為 「暫停」。 5. 倒數至 0 停止,按鈕顯示為「開始」。 6. 當右邊標籤顯示為 0 時,不能執行倒數,必須在在文 字欄輸入時間。 7. 在文字欄按下 Enter,按鈕顯示為「暫停」,開始倒 數。 25.

(26) CountDown 程式碼 (1) 1. 在文字欄 tfInput 輸入,右邊標籤同時顯示輸 入值。程式碼: private void tfInputCaretUpdate(javax.swing.event.CaretEvent evt) { lbCounter.setText(tfInput.getText()); }. 2. 在文字欄按下 Enter,按鈕顯示為「暫停」, 開始倒數。程式碼: private void tfInputActionPerformed(java.awt.event.ActionEvent evt) { btnStartActionPerformed(evt); // 在文字欄按下 Enter 鍵執行 } 26.

(27) CountDown 程式碼 (2) 3. 按鈕的程式碼: private void btnStartActionPerformed(java.awt.event.ActionEvent evt) { if (lbCounter.getText().equals("0")) return; // 計時器已歸零則不執行動作. if (btnStart.getActionCommand().equals("開始") || btnStart.getActionCommand().equals("繼續")) { btnStart.setText("暫停"); // 將按鈕顯示的文字更改為"暫停" timer.start(); // 啟動計時器 } else { btnStart.setText("繼續"); // 將按鈕顯示的文字更改為"繼續" timer.stop(); // 停止計時器 } } 27.

(28) CountDown 程式碼 (3) 4. Timer 物件 timer,程式碼: // 定義執行計時的 Timer 物件 Timer timer = new Timer(1000, // 每隔 1 秒發出 ActionEvent 事件 new ActionListener() { // 定義回應事件的監聽器物件 private int value; @Override public void actionPerformed(ActionEvent e) { value = Integer.valueOf(lbCounter.getText()); // 取得目前計數值 value--; lbCounter.setText(String.valueOf(value)); if (value == 0) { btnStart.setText("開始"); timer.stop(); } // 將按鈕顯示的文字更改為"開始",並且停止計時器 } }); 28.

(29) 練習 3. 在計時器範例中,新增一個按鈕「重新設定」。  按下「重新設定」按鈕,將文字欄及標籤數 字歸零。  當倒數進行中, 「重新設定」按鈕功能停 止;當倒數暫停時,按鈕顯示「繼續」,標 籤數字暫停變化,「重新設定」按鈕啟動。 – 提示:按鈕具有 setEnabled( ) 方法,傳送參 數 true,啟動按鈕功能,參數 false 按鈕功 能停止。. 29.

(30) 英文字母打字練習 • 範例:TypingGame • 視窗畫面. 30.

(31) 英文字母打字練習功能 1. 按「開始」按鈕後,隨機產生英文字母落下。 2. 在文字欄輸入字母,若有符合畫面上的字母, 則字母消失;重新隨機產生字母,再從最上 面落下。 3. 在文字欄輸入字母後,自動清除文字欄輸入。. 31.

(32) 英文字母打字練習程式碼 (1) 1. 在畫面先配置 10 個標籤 (lb0, …, lb9),宣告 一個標籤陣列 lbArray,然後將預先配置的標 籤放入標籤陣列 lbArray 中。程式碼:  private JLabel [] lbArray;  標籤儲存到 lbArray[] 陣列,設定標籤位置 private void myinitComponents() { lbArray = new JLabel[maxNo]; lbArray[0] = lb0; lbArray[1] = lb1; lbArray[2] = lb2;lbArray[3] = lb3; lbArray[4] = lb4; lbArray[5] = lb5; lbArray[6] = lb6;lbArray[7] = lb7; lbArray[8] = lb8; lbArray[9] = lb9; for (int i = 0; i < maxNo; i++) x[i] = (int) lbArray[i].getLocation().x; // 取得標籤的 x 位置 } 32.

(33) 英文字母打字練習程式碼 (2)  myinitComponents() 在視窗建構函數中被 呼叫執行。 public TypingGame() { initComponents(); myinitComponents(); }. 2. 定義變數 private int [] x = new int [10]; // 儲存標籤的x位置 // 儲存標籤的y位置,初始都是5 private int [] y = {5, 5, 5, 5, 5, 5, 5, 5, 5, 5}; private final int maxNo = 10; // 標籤數 private final int moveSteps = 3; // 標籤每次移動點數最大值 33.

(34) 英文字母打字練習程式碼 (3) 3. 設定標籤內容與字體顏色,程式碼: private void setLabel(int i) { int r = (int) (Math.random() * 26); char ch = (char) ('a' + r); lbArray[i].setText(String.valueOf(ch)); r = (int) (Math.random() * 255); int g = (int) (Math.random() * 255); int b = (int) (Math.random() * 255); lbArray[i].setForeground(new Color(r,g,b)); }. 34.

(35) 英文字母打字練習程式碼 (4) 4. 「開始」按鈕的程式碼 private void btnStartActionPerformed(java.awt.event.ActionEvent evt) { timer.start(); tfInput.requestFocus(); // 自動讓游標移到文字欄 for (int i = 0; i < maxNo; i++) setLabel(i); }. 35.

(36) 英文字母打字練習程式碼 (5) 5. 文字欄的程式碼 private void tfInputCaretUpdate(javax.swing.event.CaretEvent evt) { for (int i = 0; i < maxNo; i++) if (tfInput.getText().equals(lbArray[i].getText())) { y[i] = 5; setLabel(i); } } private void tfInputKeyReleased(java.awt.event.KeyEvent evt) { tfInput.setText(""); // 清除文字欄中的文字 }. 36.

(37) 練習 4. 在英文字母打字練習的程式中增加功能:  計時一分鐘練習,時間到停止執行。  執行時,動態顯示成績,包括: A. 按下的總字母數。 B. 正確按下的字母數。.  時間到時,顯示最後的成績。. 37.

(38) 範例:檔案操作 • 範例:FileEx • 視窗元件配置 – 在 Frame 上放置 1 個 Scroll Pane – 在 Scroll Pane 中放置 1 個 Text Area – 3 個按鈕. 38.

(39) 基本的檔案操作 (1) 1. 建立File物件 File file = new File(FILENAME);. // 宣告檔案的File物件. 2. 開啟檔案 FileReader fr = new FileReader(FILENAME);. // 讀取檔案. FileWriter fw = new FileWriter(FILENAME);. // 寫入檔案. 3. 檔案緩衝物件 BufferedReader br = new BufferedReader(fr);. // 讀取緩衝區. BufferedWriter bw = new BufferedWriter(fw);. // 寫入緩衝區 39.

(40) 基本的檔案操作 (2) 4. 讀取 str = br.readLine();. 5. 寫入 bw.write(str); bw.flush(); // 清空輸出串流,並將資料寫入. 6. 關閉緩衝區/檔案 br.close(); fr.close();. bw.close(); fw.close(); 40.

(41) 檔案的例外處理 • Java 在處理檔案時,必須使用例外處理 try {…} catch { … } 機制。. 41.

(42) FileEx 程式碼 (1) 1. 定義變數 // 操作檔案的檔案名稱 final static String FILENAME = "myfile.txt";. 2. 「清除文字區內容」按鈕 private void btnClearActionPerformed(java.awt.event.ActionEvent evt) { taContent.setText(""); }. 3. 「讀取檔案myfile.txt」按鈕 private void btnLoadActionPerformed(java.awt.event.ActionEvent evt) { loadFile(); } 42.

(43) FileEx 程式碼 (2) 4. 「資料寫回檔案」按鈕 private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) { saveFile(); }. 5. 讀取檔案 private void loadFile() { // 讀入檔案內容 File file = new File(FILENAME); // 宣告檔案的File物件 String str, s; if (!file.exists()) { // 若是檔案不存在,則開一個新的空檔案。 try { FileWriter fw = new FileWriter(FILENAME); fw.close(); } catch(Exception ex) { ex.printStackTrace(); } 43.

(44) FileEx 程式碼 (3) } else { // 檔案存在,讀取檔案內容存成字串s。 try { FileReader fr = new FileReader(FILENAME); BufferedReader br = new BufferedReader(fr); str = br.readLine(); s = ""; while (str != null) { s = s + str + "\n"; str = br.readLine(); } taContent.setText(s); // 在Text Area中顯示資料 br.close(); fr.close(); } catch(Exception ex) { ex.printStackTrace(); } } // End of if … else } 44.

(45) FileEx 程式碼 (1) 6. 資料存入檔案 private void saveFile() { // 資料存入檔案 String str = taContent.getText(); try { FileWriter fw = new FileWriter(FILENAME); BufferedWriter bw = new BufferedWriter(fw); bw.write(str); bw.flush(); // 清空輸出串流,並將資料寫入 bw.close(); fw.close(); } catch(Exception ex) { ex.printStackTrace(); } } 45.

(46) 練習 5. 在英文字母打字練習的程式中增加功能:  以檔案記錄一分鐘練習的最高成績。  顯示最高成績於視窗中。. 46.

(47)

參考文獻

相關文件

public static double calculate(int i, int j) throws ArithmeticException,

National Taiwan University July 9, 2005 Page 5..

Contains the core Swing components, including most of the model interfaces and support

• Copy a value from the right-hand side (value or expression) to the space indicated by the variable in the left-hand side.. • You cannot write codes like 1 = x because 1 cannot

• Instead, static nested classes do not have access to other instance members of the enclosing class. • We use nested classes when it

• Instead, static nested classes do not have access to other instance members of the enclosing class. • We use nested classes when it

‡圖形使用者介面( graphical user interface GUI). ‡圖形使用者介面( graphical user

有關於 Java 程式語言,下列何者敘述不正確?(A)Java 程式語言透過 extends 提供多重繼承 (Multiple