Java 輸入框事件監聽教程.

一、教程

1.創建一個新的Frame,這裏使用新建類 My輸入框事件監聽Frame 實現,(記得繼承Frame)

如何新建一個Frame 類教程點擊跳轉

2.新建一個 TextField 文本域並添加至 1步驟新建的窗口

  TextField textField = new TextField();//build a TextField ,difference of the TextArea
  this.add(textField);//add textField to MyFrame

3.新建一個事件的監聽( MyActionListener輸入框事件監聽 )繼承 implements 動作監聽 ActionListener;並且使用 alt+insert 實現重構唯一的方法 actionPerformed(ActionEvent e)

class MyActionListener輸入框事件監聽 implements ActionListener {}

代碼塊裏完成 對 TextField 的監聽和 內容的輸出

1.e.getSource();查看源碼(ctrl+鼠標左鍵)得知可以獲取 事件的Source返回Object類
2.將 e.getSource() 強制轉化爲 TextField類型
3.textField.getText() 獲取文本框的文本,(查看源碼得知返回String可以直接輸出)
4.textField.setText("");文本框文本重置,查看源碼得知需要傳入參數 String

class MyActionListener輸入框事件監聽 的代碼
class MyActionListener輸入框事件監聽 implements ActionListener {


  @Override
  public void actionPerformed(ActionEvent e) {
      e.getSource();//see the source code ,it will return a Object
      TextField textField = (TextField) e.getSource();//強制轉換coercion
      textField.getText();//see the source code ,it will return a String
      System.out.println(textField.getText());
      textField.setText("");//see the source code,it need pass a String
  }
}

4.將3中新建的監聽對象填加到 textField 中

textField.addActionListener(myActionListener);

總代碼 。

package GUI.輸入框事件監聽;

import GUI.MyClass.MySystemExit;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Demo {
  public static void main(String[] args) {
      new My輸入框事件監聽Frame();
  }
}

class My輸入框事件監聽Frame extends Frame {
  My輸入框事件監聽Frame() {
      TextField textField = new TextField();//build a TextField ,difference of the TextArea
      this.add(textField);//add textField to MyFrame
      //Listener the text of the textField,use,監聽輸入的文字
      MyActionListener輸入框事件監聽 myActionListener = new MyActionListener輸入框事件監聽();
      //add the ActionListener to the TextField,按下回車就會觸發事件
      textField.addActionListener(myActionListener);
      //設置替換編碼,密碼專用。 setting the replacement character.
//        textField.setEchoChar('*');
      //setting the visibility
      this.setVisible(true);
      this.setLocation(100, 100);
      this.setSize(400, 400);
      textField.setBackground(new Color(99, 255, 240));


      new MySystemExit(this);


  }
}

class MyActionListener輸入框事件監聽 implements ActionListener {


  @Override
  public void actionPerformed(ActionEvent e) {
      e.getSource();//see the source code ,it will return a Object
      TextField textField = (TextField) e.getSource();//強制轉換coercion
      textField.getText();//see the source code ,it will return a String
      System.out.println(textField.getText());
      textField.setText("");//see the source code,it need pass a String
  }
}

二、使用textField.setEchoChar(’*’); 實現密碼樣式,在文本框裏看到的文字轉換爲 *

在 一 中的 textField中添加 一行代碼

在這裏插入圖片描述

效果展示

在這裏插入圖片描述
在這裏插入圖片描述

回車後效果

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章