2

组合框有两个值:ANDOR

我为 Combo 编写了属性更改侦听器,当且仅当当前选择的值和以前的值不同时,触发此事件。但是我需要即使值相同也应该触发此事件?

这是我的示例代码片段:

public void setRuleOperation(String ruleOperation) {
    String oldValue = this.ruleOperation;

    if (oldValue != ruleOperation) {
        this.ruleOperation = ruleOperation;
        getPropertyChangeSupport().firePropertyChange(PROPERTY_OPERATION, oldValue, null);
    }
    
    this.ruleOperation = ruleOperation;
} 
4

1 回答 1

0

一种可能性是:

  • 使用该对象创建一个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”冒泡两个不同的键按下/释放事件。

于 2020-07-25T23:32:00.753 回答