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<ValueChangeListener> listeners = new Vector<ValueChangeListener>();

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<ValueChangeListener> currentListeners = null;
synchronized (this) {
currentListeners = (Vector<ValueChangeListener>) 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);

}

}

---------------------
作者:teamlet
来源:CSDN
原文:https://blog.csdn.net/teamlet/article/details/42618733
版权声明:本文为博主原创文章,转载请附上博文链接!


原网址: 访问
创建于: 2022-11-17 22:17:22
目录: default
标签: 无

请先后发表评论
  • 最新评论
  • 总共0条评论