java监听接口的问题,小弟感激不尽

来源:百度知道 编辑:UC知道 时间:2024/09/22 19:41:00
import java.awt.*;
import java.awt.event.*;
public class EventTexter1 extends Frame{

static int count=1;

public EventTexter1 (String title){super(title);}

public static void main(String args[]){
EventTexter1 f=new EventTexter1 ("hello");
f.setLayout(new FlowLayout());
final Button b=new Button("1");
b.addActionListener(new ActionListener(){ //主要从这解释到下面 class
public void actionPerformed(ActionEvent evt){
b.setLabel(new Integer(++count).toString());
}
});//到这里

f.add(b);
f.setSize(100,100);
f.setBackground(Color.blue);
f.setVisible(true);
}
}

这个是ActionListener这个接口里面的方法

用于接收操作事件的侦听器接口。对处理操作事件感兴趣的类可以实现此接口,而使用该类创建的对象可使用组件的 addActionListener 方法向该组件注册。在发生操作事件时,调用该对象的 actionPerformed 方法。

Java Swing中处理各组件事件的一般步骤是:

1. 新建一个组件(如JButton)。

2. 将该组件添加到相应的面板(如JPanel)。

3. 注册监听器以监听事件源产生的事件(如通过ActionListener来响应用户点击按钮)。

4. 定义处理事件的方法(如在ActionListener中的actionPerformed中定义相应方法)。

以上步骤我们可以用多种方法实现。但人们通常用二种方法。第一种方法是只利用一个监听器以及多个if语句来决定是哪个组件产生的事件;第二种方法是使用多个内部类来响应不同组件产生的各种事件,其具体实现又分两种方式,一种是匿名内部类,一种是一般内部类。

整体上讲,就是给button添加一个事件监听,这个事件是通过一个匿名类直接实现监听接口来实现的。
逐步说明,从外到内:
1.addActionListener()就是给button添加监听。
2.ActionListener是一个接口,actionPerformed()是这个接口中的方法。
new ActionListener(){
public void actionPerformed(ActionEvent evt){
b.setLabel(new Integer(++count).toString());
}
}
这段代码就是用一个匿名类来实现接口ActionListener中的actionPerformed()。

匿名类的使用在swt中使用非常普遍,主要用于只使用一次的监听。

b.addActionListener(new ActionListener()---给按钮b 加一个监听