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中添加 一行代码

在这里插入图片描述

效果展示

在这里插入图片描述
在这里插入图片描述

回车后效果

在这里插入图片描述

发布了56 篇原创文章 · 获赞 2 · 访问量 473

猜你喜欢

转载自blog.csdn.net/jarvan5/article/details/105601531