为什么我的propertyylistener没有火?

时间:2012-05-14 19:33:15

标签: java propertychangelistener

这就是我的代码:

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);
 }

}  

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

1 个答案:

答案 0 :(得分: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

我认为你错过了一些例子。