Java event事件监听属性值变化 demo
Posted teamlet
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
以上是关于Java event事件监听属性值变化 demo的主要内容,如果未能解决你的问题,请参考以下文章