首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java 定做事件

2012-08-26 
java 定制事件package eventimport java.util.Vectorpublic class A {?private Vector aListeners new

java 定制事件

package event;

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 static void main(String[] args) {

??A a = new A();
??AListener aL1 = new AListenerImpl();
??AListener aL2 = new AListenerImpl();
??a.addAListener(aL1);
??a.addAListener(aL2);
??a.setValue(123);
??a.setValue(1234);

?}
}

?

package event;

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);
??setValue(newValue);
?}

?public void setValue(int value) {
??this.value = value;
?}

?public int getValue() {
??return value;
?}
}

?

package event;

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

?

package event;

public class AListenerImpl implements AListener {

?@Override
?public void performed(AEvent e) {
??// 要处理的

??System.out.println("e.getValue():" + e.getValue());
?}

}

热点排行