`
huxiuliang
  • 浏览: 117228 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

java的监听方法

    博客分类:
  • Java
阅读更多


package dome1;

import java.util.Vector;

/*
 在一个类A中写一个事件evt, 
 当A中的某个值变化时,就触发evt, 
 
 然后写另外一个类B,监听A中的event1事件,  */

public class A {
   
    private Vector aListeners = new Vector();
   
    private int value;
   
    public int getValue() {

    return value;
    }
   
    public void setValue(int newValue) {

    if (value != newValue) {
        value = newValue;
        AEvent evt = new AEvent(this, value);//可以写到外面取初始化
        // 如果值改变的话,就触发事件
        fireAEvent(evt);
    }
    }
   
    public synchronized void addAListener(AListener a) {

    aListeners.addElement(a);
    }
   
    public synchronized void removeAListener(AListener a) {

    aListeners.removeElement(a);
    }
   
    public void fireAEvent(AEvent evt) {

    Vector currentListeners = null;
    synchronized (this) {
        currentListeners = (Vector) aListeners.clone();//返回副本
    }
    for ( int i = 0 ; i < currentListeners.size() ; i++) {
        AListener listener = (AListener) currentListeners.elementAt(i);
        listener.doSth(evt);
    }
    }
}


----------------------------

package dome1;

import java.util.EventObject;


//定义事件
public class AEvent extends EventObject {
   
    private int value;
   
      
    public AEvent(Object source, int newValue) {

    super(source);
    value = newValue;
    }

  
}
------------------

package dome1;


//定义接口,当事件触发时调用
public interface AListener extends java.util.EventListener {
   
    public void doSth(AEvent e);
}

-----------------------


package dome1;

class B implements AListener {
   
    public B() {

    A a = new A();
    a.addAListener(this);
    try {
        Thread.sleep(3000);
        // 改变属性,触发事件
        a.setValue(1);
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }
    }
   
    public static void main(String[] args) {

    new B();
    }
   
    public void doSth(AEvent e) {

    System.out.println("改变事件发生");
   
    }
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics