GUI 输入框监听事件

编写代码 TestTest01测试类

package com.xiang.lesson02;

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

public class TestTest01 {
    public static void main(String[] args) {
        new MyFrame();
    }
}

class MyFrame extends Frame {
    public MyFrame() {
//        文本框
        TextField field = new TextField();
        add(field);

//        监听文本框输入的东西
        MyActionListener2 listener2 = new MyActionListener2();
        field.addActionListener(listener2);

//        设置替换编码
//        field.setEchoChar('*');

        pack();
        setVisible(true);
        setBackground(Color.green);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

class MyActionListener2 implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        TextField field= (TextField) e.getSource(); //获得资源
        //获得输入框中的文本;
        System.out.println(field.getText());
//        清空
        field.setText("");
    }
}

运行结果

posted @ 2021-08-05 18:50  阿向向  阅读(67)  评论(0编辑  收藏  举报