Java 基礎【04】Swing 組件事件注冊


    聰明出於勤奮,天才在於積累。——華羅庚

   對上次的三個問題的個人理解: 

   1) 程序首先是從main函數開始執行的,假設main 函數不是 static ,就要先實例化這個類,然后調用 main 方法,這似乎是不現實的. 其次 用 static 修飾的 main 方法是存儲在靜態的存貯區當中的,也就是說在創建一個類之后,main 函數就已經存在了,去掉 static 修飾之后,編譯可以通過,但是不能執行。
   2)查 API之后才發現BufferedRead 對象的 readLine()方讀到的數據是,讀到有換行的地方為一行,直接用 readLine 判斷的時候已經讀入一行了,在輸出數據時就會隔行輸出。

 FileReader file=new FileReader("C:\\123.txt");
            BufferedReader br1=new BufferedReader(file);
                       //判斷的時候已經讀入一行
            while((br1.readLine())!=null)
            {   //輸出的是第二行的內容
                System.out.println(br1.readLine());
            }

所以用一個臨時的字符串變量來存儲讀到的數據,程序改改這樣就可以了:

    FileReader file=new FileReader("C:\\123.txt");
            BufferedReader br1=new BufferedReader(file);
            
            String cd;
            while((cd=br1.readLine())!=null)
            {
                System.out.println(cd);
            }

3)如果將客戶端、輸入流、輸出流的初始化全部放進 Send 按鈕的事件當中時,程序會達到我想要的效果,點擊連接之后就會有客戶端連接上去,但總覺得這樣會有其他的安全隱患,總有一天它會暴漏的。

     今天要記錄在這里的是老師隨堂布置的一個小程序,實現一個計算器的雛形,里面只有加減運算,對其中的按鈕注冊有了一點新的認識,還是將代碼貼出來先。

  import javax.swing.*;
  import java.awt.*;
  import java.awt.event.*; 


public class ComboBoxTest extends JFrame{     
      private JButton done =new JButton(" Done ");
      private JButton clear=new JButton(" Clear ");      
      private JLabel  label = new JLabel("Please choose serverID:0(+)and1(-)");      
      
 public  ComboBoxTest(){     
     //添加一個組合框並設置兩個選項
      final JComboBox c = new JComboBox();
      int [] array = {0,1};
      c.addItem(array[0]);
      c.addItem(array[1]);

      final JTextField operand1=new JTextField(10);      //添加第一個操作數為輸入文本框,占8列
      final JLabel t=new JLabel("+");                     //初始化中間的操作符為“+”號
      final JTextField operand2=new JTextField(10);      //第二個操作符
      final JTextField result=new JTextField(4);         //結果的文本域 ,初始化占4列
      
      //給組合框c注冊一個事件,當組合框選項發生變化的時候,觸發的相應事件
      c.addActionListener(new ActionListener() {      
          public void actionPerformed(ActionEvent e) {
              if(c.getSelectedIndex()==0)   //選項為“0”的時候 令中間的操作符顯示“+”號
                t.setText(" + ");           
               else  t.setText(" - ");        
         }
        });
      //給按鈕Done注冊一個事件,當中間的操作符不同時進行不同的操作
       done.addActionListener(new ActionListener(){   
            public void actionPerformed(ActionEvent e) {
                if(c.getSelectedIndex()==0)   
                {
                    //當中間的操作符為“+”號時,進行兩個操作數的加法 ,文本域的get()方法返回的是字符串,進行強制轉換
                     int a=Integer.parseInt(operand1.getText())+Integer.parseInt(operand2.getText());                     
                     result.setText("="+" "+a+" ");  //設置結果顯示相應的結果
                   }          
              else {
                  //當中間的操作符為“-”號的時候,進行兩個操作數的減法
                int a=Integer.parseInt(operand1.getText())-Integer.parseInt(operand2.getText());                     
                result.setText("="+" "+a+" ");
              }    
            }              
          });
    // 給按鈕clear注冊一個事件,清空兩個操作數和結果的內容
     clear.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {            
            operand1.setText("");    //清空操作數1
            operand2.setText("");    //清空操作數2
            result.setText("");      //清空結果框
            }               
          });    
      setLayout(new FlowLayout());
      add(label);                   
      add(c);
      add(operand1);
      add(t);
      add(operand2);
      add(result);
      add(done);
      add(clear); 
      setSize(350,140);  
      setVisible(true);   
     }
 
   public static void main(String[] args) {
       new ComboBoxTest(); 
         }
}

上面的代碼中給選項框、“done”、"clear"按鈕注冊事件的時候所用的都是匿名類,這個類的創建就是為了給相應的組件添加事件,還可以這樣寫,用里面的“clear”這個按鈕來做個例子。

實現 ActionListener 抽象類當中的唯一的一個接口函數,為此定義一個 ButtonListener 監聽器的對象

class ButtonListener implements ActionListener{
       public void actionPerformed(ActionEvent e){
            operand1.setText("");    //清空操作數1
            operand2.setText("");    //清空操作數2
            result.setText("");      //清空結果框             
       }
   }

類屬性當中需要定義一個 ButtonListener 的對象屬性:

private ButtonListener clearaction = new ButtonListener();

最后一個步驟就是將這個按鈕監聽器的事件對象注冊給按鈕:

clear.addActionListener(clearaction);

  個人總結:

    這一種注冊事件的方式大致過程是這樣的 ButtonListener =》 ActionListener => 注冊給按鈕,和匿名類相比,缺點是代碼量有點多,但假設你有N個打算具備這種

功能的按鈕並且事件實現的方法比較復雜時,就可以實現一個 ActionListener 的對象,同時定義N個 ButtonListener 監聽器對象,將相同的事件實現注冊給按鈕就可以了,相比之下匿名類在這種情形下面會有很大的工作量,代碼量會激增。

     還可以通過事件 e.getSource()方法將所有的事件處理放進一個函數當中,這樣似乎維護起來要更方便一點,在類的聲明當中要強調實現接口中的抽象函數。

public class ComboBoxTest extends JFrame implements ActionListener

 具體的實現過程如下:

  public void actionPerformed(ActionEvent e){
       if(e.getSource()==c){
              if(c.getSelectedIndex()==0)   //選項為“0”的時候 令中間的操作符顯示“+”號
                    t.setText(" + ");           
                    else  t.setText(" - ");     
       }
       
       if(e.getSource()==done){
            if(c.getSelectedIndex()==0)   
            {
                //當中間的操作符為“+”號時,進行兩個操作數的加法 ,文本域的get()方法返回的是字符串,進行強制轉換
                 int a=Integer.parseInt(operand1.getText())+Integer.parseInt(operand2.getText());                     
                 result.setText("="+" "+a+" ");  //設置結果顯示相應的結果
               }          
          else {
              //當中間的操作符為“-”號的時候,進行兩個操作數的減法
            int a=Integer.parseInt(operand1.getText())-Integer.parseInt(operand2.getText());                     
         result.setText("="+" "+a+" ");
          }      
       }       
       if(e.getSource()==clear){
           operand1.setText("");    //清空操作數1
            operand2.setText("");    //清空操作數2
            result.setText("");      //清空結果框    
       }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM