1

这就是我的代码的样子:

Class A {

  private boolean valueChanged;

  public static void main(String args[]) {

    B obj = new B();
    obj.addPropertyChangeListener("valueChanged", new ValueChangeListener());
    obj.someMethodThatFiresChange();
 }

  private class ValueChangeListener implements PropertyChangeListener {
    public void propertyChange(PropertyChangeEvent evt) {
         if(Boolean.TRUE.equals(evt.getNewValue()) {
            doSomething(); //code never breaks here!!
         }
    }
  }

}

Class B {

 private boolean valueChanged;

 public void setValueChanged(boolean b) { 

     boolean oldVal = valueChanged;
     valueChanged = b;
     firePropertyChange("valueChanged", oldVal, valueChanged);
 }

 public void someMethodThatFiresChange() {
     setValueChanged(true);
 }

}  

然而,这段代码似乎不起作用——它永远不会到达事件触发时应该执行的块!我在这里做错了什么?

4

1 回答 1

2

这对我有用:

   public class A {

    /**
     * @param args
     */
    public static void main(String[] args) {

        B obj = new B();
        obj.addPropertyChangeListener("valueChanged", new ValueChangeListener());
        obj.someMethodThatFiresChange();

    }

    private static final class ValueChangeListener implements PropertyChangeListener {

        public void propertyChange(PropertyChangeEvent event) {
            System.out.println("huhu");

            if(Boolean.TRUE.equals(event.getNewValue())) {
                System.out.println("haha");
             }

        }

    }

    private static final class B {

        private boolean valueChanged;

        private final PropertyChangeSupport pcSupport = new PropertyChangeSupport(this);

        public void setValueChanged(boolean b) {

            boolean oldVal = valueChanged;
            valueChanged = b;
            pcSupport.firePropertyChange("valueChanged", oldVal, valueChanged);
        }

        public void someMethodThatFiresChange() {
            setValueChanged(true);
            setValueChanged(false);
            setValueChanged(true);
        }

        public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
            pcSupport.addPropertyChangeListener(propertyName, listener);
        }

        public void addPropertyChangeListener(PropertyChangeListener listener) {
            pcSupport.addPropertyChangeListener(listener);
        }
    }

   }

输出:

huhu
haha
huhu
huhu
haha

我认为您在示例中遗漏了一些东西。

于 2012-05-14T19:50:28.213 回答