`
gudujianxuehu
  • 浏览: 96173 次
  • 来自: ...
社区版块
存档分类
最新评论

java监听

阅读更多
感觉这段代码没什么意义,但还是放上面,方便以后查找吧。

import java.util.Vector;

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.performed(evt);
		}
	}
}

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

import java.util.EventObject;

// 定义事件
public class AEvent extends EventObject {
	private int value;

	public AEvent(Object source) {
		super(source);
	}

	public AEvent(Object source, int newValue) {
		super(source);
		value = newValue;
	}
}

class B {
	public B() {
		A a = new A();
		a.addAListener(new AListener() {
			public void performed(AEvent e) {
				System.out.println("a.监听1");

			}
		});
		a.addAListener(new AListener() {
			public void performed(AEvent e) {
				System.out.println("a.监听2");

			}
		});
		a.addAListener(new AListener() {
			public void performed(AEvent e) {
				System.out.println("a.监听3");

			}
		});
		a.setValue(1);
		a.setValue(2);
	}

	public static void main(String[] args) {
		B b = new B();
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics