事件最基本的处理过程:
l 定义实现事件监听接口类
l 创建事件监听器
l 向事件源注册监听器时象
下面通过程序实例让大家熟悉一下整个事件处理的过程。这个实例主要是实现当单击按钮组件时,文本框中的文本被清空的动作事件,实例程序代码如下所示:
public class BWF {
static final int WIDTH=300;
static final int HEIGHT=200;
static JTextField tf=new JTextField(20);
public static void main(String[] args) {
JFrame jf=new JFrame("博为峰教育");
jf.setSize(WIDTH, HEIGHT);
JPanel contentPane=new JPanel();
contentPane.setLayout(new BorderLayout());
JButton b=new JButton("清空文本框的信息");
contentPane.add(tf, "North");
contentPane.add(b, "South");
b.addActionListener(new ActionHandler());//创建一个事件监听器,向事件源注册
jf.setContentPane(contentPane);
jf.setVisible(true);
}
}
//定义实现事件监听类
class ActionHandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
new BWF().tf.setText("");
}
}