如果在swing Jcombo框中新旧值相等,如何触发属性更改侦听器

时间:2014-03-06 12:05:38

标签: java swing jcombobox propertychangelistener propertychangesupport

我有一个组合框,它有两个值“AND”和“OR”

我为Combo编写了属性更改侦听器,因为此事件触发, if和only当前选择的值和先前的值是不同的... 但我需要即使值相同也应该触发此事件吗?

这是我的示例代码段:

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

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

    this.ruleOperation = ruleOperation;
} 

1 个答案:

答案 0 :(得分:0)

一种可能性包括:

  • 使用PropertyChangeEvent对象创建一个PropertyChangeSupport实例。
  • 创建新的fire方法来模拟firePropertyChange
  • 遍历属性更改侦听器。
  • 使用新的事件实例为每个侦听器调用propertyChange

Et lavoilà,防止在旧值等于新值时触发的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”冒泡两个不同的按键/释放事件。