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

}

你可能感兴趣的:(java)