一种可能性是:
- 使用该对象创建一个
PropertyChangeEvent
实例。PropertyChangeSupport
- 创建一个新
fire
方法来模拟firePropertyChange
.
- 遍历属性更改侦听器。
propertyChange
使用新的事件实例为每个侦听器调用。
等等,if
当旧值等于新值时阻止触发的条件已被绕过。
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
/**
* Responsible for notifying its list of managed listeners when property
* change events have occurred. The change events will only be fired if the
* new value differs from the old value.
*
* @param <P> Type of property that, when changed, will try to issue a change
* event to any listeners.
*/
public abstract class PropertyDispatcher<P> {
private final PropertyChangeSupport mDispatcher =
new PropertyChangeSupport( this );
/**
* Adds a new listener to the internal dispatcher. The dispatcher uses a map,
* so calling this multiple times for the same listener will not result in
* the same listener receiving multiple notifications for one event.
*
* @param listener The class to notify when property values change, a value
* of {@code null} will have no effect.
*/
public void addPropertyChangeListener(
final PropertyChangeListener listener ) {
mDispatcher.addPropertyChangeListener( listener );
}
@SuppressWarnings("unused")
public void removePropertyChangeListener(
final PropertyChangeListener listener ) {
mDispatcher.removePropertyChangeListener( listener );
}
/**
* Called to fire the property change with the two given values differ.
* Normally events for the same old and new value are swallowed silently,
* which prevents double-key presses from bubbling up. Tracking double-key
* presses is used to increment a counter that is displayed on the key when
* the user continually types the same regular key.
*
* @param p Property name that has changed.
* @param o Old property value.
* @param n New property value.
*/
protected void fire( final P p, final String o, final String n ) {
final var pName = p.toString();
final var event = new PropertyChangeEvent( mDispatcher, pName, o, n );
for( final var listener : mDispatcher.getPropertyChangeListeners() ) {
listener.propertyChange( event );
}
}
}
这在使用 为按键触发多个事件时很有用PropertyChangeSupport
。键入“Hello”会冒泡为“Helo”,因为旧按键事件(“l”)与第二个按键事件(“l”)匹配。以这种方式直接通知允许双“l”冒泡两个不同的键按下/释放事件。