gpt4 book ai didi

java - 为什么我的 PropertyListener 不触发?

转载 作者:行者123 更新时间:2023-11-30 04:47:44 25 4
gpt4 key购买 nike

这就是我的代码:

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

}

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

最佳答案

这对我有用:

   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

我认为您在示例中遗漏了一些内容。

关于java - 为什么我的 PropertyListener 不触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10589880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com