学海拾遗

生活、技术、思想无处不在学习
posts - 52, comments - 23, trackbacks - 0, articles - 3
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

Java中的事件监听

Posted on 2007-03-17 02:50 tanzek 阅读(1831) 评论(0)  编辑  收藏

继续在看Java Tutorial,不过已经到了GUI了,呵呵!~
在"Introduction to Event Listeners"中,看到了JAVA的事件监听机制。

实现事件监听机制,需要有如下三件事情:


1、In the declaration for the event handler class, one line of code specifies that the class either implements a listener interface or extends a class that implements a listener interface. For example:
 public class MyClass implements ActionListener {

       在每个事件处理类的声明中,其中有代码指明此类实现某个监听器(Listener)接口或者继承自某个实现了监听器(Listener)接口的类,例如:
      
public   class  MyClass implement ActionListener {


2、Another line of code registers an instance of the event handler class as a listener on one or more components. For example:
 someComponent.addActionListener(instanceOfMyClass);

       另外有代码注册一个事件处理类的实例到一个或多个部件的接口(Listener)上,例如:
 someComponent.addActionListener(instanceOfMyClass);


3、The event handler class has code that implements the methods in the listener interface. For example:
 public void actionPerformed(ActionEvent e) {
     ...//code that reacts to the action...
 }

      事件处理类实现了监听器(Listener)接口中的方法(抽象方法),例如:
 
public   void  actionPerformed(ActionEvent e) {
     ...//code that reacts to the action...
 }


 


事件监听模型如下图所示:
ActionEventModel.bmp

同时,其实事情监听的基本内容就是这些了,不过其中应该注意的是JAVA的多监听器的使用:
MultiListener.bmp
在上图可以看出,JAVA中的一个事件清所产生的事件对象可以发送至多个事件监听接口,那么就有如下的程序片块:
 1public class MultiListener  implements ActionListener {
 2    
 3    //where initialization occurs:
 4        button1.addActionListener(this);
 5        button2.addActionListener(this);
 6
 7        button2.addActionListener(new Eavesdropper(bottomTextArea));
 8    }

 9
10    public void actionPerformed(ActionEvent e) {
11        topTextArea.append(e.getActionCommand() + newline);
12    }

13}
14
15class Eavesdropper implements ActionListener {
16    
17    public void actionPerformed(ActionEvent e) {
18        myTextArea.append(e.getActionCommand() + newline);
19    }

20}

21
22
其中的button2分别注册了MultiListener和Eavesdropper两个类的对象,按照前面那个图的意思,那么button2所产生的事件对象会被分别发至MultiListener和Eavesdropper。
呵,大家可以测试下哦!`
可以运行JAVA的测试程序: Run MultiListener

只有注册用户登录后才能发表评论。


网站导航: