Java event事件监听属性值变化 demo

1、定义一个 ValueChangedEvent 

ValueChangedEvent用于在设置属性值的时候,触发事件。

 
package org.teamlet;

import java.util.EventObject;

public class ValueChangeEvent extends EventObject {

	/**
	 * 
	 */
	private static final long serialVersionUID = 767352958358520268L;
	private int value;

	public ValueChangeEvent(Object source) {
		this(source, 0);
	}

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

	public int getValue() {
		return value;
	}
}

 

2、定义监听接口 ValueChangeListener

ValueChangeListener 提供属性值变化的接口。

 
package org.teamlet;

public interface ValueChangeListener extends java.util.EventListener {

	public abstract void performed(ValueChangeEvent e);
}
 

3、事件的产生者

EventProducer提供了监听容器listenerRegister,负责消费者的注册。

 
package org.teamlet;

public class EventProducer {
	ListenerRegister register = new ListenerRegister();
	private int value;

	public int getValue() {
		return value;
	}

	public void setValue(int newValue) {
		if (value != newValue) {
			value = newValue;
			ValueChangeEvent event = new ValueChangeEvent(this, value);
			fireAEvent(event);
		}
	}

	public void addListener(ValueChangeListener a) {
		register.addListener(a);
	}

	public void removeListener(ValueChangeListener a) {
		register.removeListener(a);
	}

	public void fireAEvent(ValueChangeEvent event) {
		register.fireAEvent(event);
	}

}
  

4、注册器

ListenerRegister负责注册和分发事件。

 
package org.teamlet;

import java.util.Vector;

public class ListenerRegister {

	private Vector listeners = new Vector();

	public synchronized void addListener(ValueChangeListener a) {
		listeners.addElement(a);
	}

	public synchronized void removeListener(ValueChangeListener a) {
		listeners.removeElement(a);
	}

	@SuppressWarnings("unchecked")
	public void fireAEvent(ValueChangeEvent evt) {
		Vector currentListeners = null;
		synchronized (this) {
			currentListeners = (Vector) listeners.clone();
		}
		for (int i = 0; i < currentListeners.size(); i++) {
			ValueChangeListener listener = (ValueChangeListener) currentListeners
					.elementAt(i);
			listener.performed(evt);
		}
	}
}
   



5、事件的消费者

EventConsumer实现ValueChangedListener,当EventProducer 发送事件时,接收事件。

 
package org.teamlet;

public class EventConsumer implements ValueChangeListener {

	@Override
	public void performed(ValueChangeEvent e) {
		System.out.println("value changed, new value = " + e.getValue());
	}
}

 

6、使用

 
package org.teamlet;

public class Main {

	public static void main(String[] args) {
		EventProducer producer = new EventProducer();
		producer.addListener(new EventConsumer());
		producer.setValue(2);

	}

}
  


Java event事件监听属性值变化 demo_第1张图片

你可能感兴趣的:(Java技术,java,event,event-based,programm)