// 说明:当点击按钮时会触发动作事件,清空文本框的数据
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class test {
static final int WIDTH = 200;
static final int HEIGHT = 300;
static JTextField l = new JTextField(20);
public static void main(String[] args) {
JFrame jf = new JFrame("测试程序");
jf.setSize(WIDTH, HEIGHT);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
jf.setContentPane(contentPane);
JButton jb = new JButton("清空文本框中的信息");
contentPane.add(l, "North");
contentPane.add(jb, "South");
ActionListener ac = new ActionHandler(); // 创建一个事件监听器
jb.addActionListener(ac); // 向事件源注册
}
}
// 定义实现事件监听类
class ActionHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
new test().l.setText("");
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class test {
static final int WIDTH = 200;
static final int HEIGHT = 300;
static JTextField l = new JTextField(20);
public static void main(String[] args) {
JFrame jf = new JFrame("测试程序");
jf.setSize(WIDTH, HEIGHT);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
jf.setContentPane(contentPane);
JButton jb = new JButton("清空文本框中的信息");
contentPane.add(l, "North");
contentPane.add(jb, "South");
ActionListener ac = new ActionHandler(); // 创建一个事件监听器
jb.addActionListener(ac); // 向事件源注册
}
}
// 定义实现事件监听类
class ActionHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
new test().l.setText("");
}
}
将事件处理过程进行总结:
(1)定义事件事件监听接口类:class ActionHandler implements ActionListener{ }
(2)创建事件监听器:ActionListener ac = new ActionHandler();
(3)向源事件注册:jb.addActionListener(ac);