【发布时间】:2021-03-22 23:44:06
【问题描述】:
我很困惑如何使用对象绑定将 ObjectProperty 绑定到另一个对象。根据我在 javaFX 文档中阅读和理解的内容,这个 MCVE 应该输出 20,但它不起作用。输出即将变为 0。
// I tried to bind the attribute B's Integer attribute in class A to class C's SimpleIntegerProperty
package sample;
import javafx.beans.binding.ObjectBinding;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
class ObjectBindingImpl extends ObjectBinding {
private A a;
public ObjectBindingImpl(A a) {
this.a = a;
bind(new SimpleObjectProperty<>(a.b));
}
@Override
protected Object computeValue() {
return a.b == null ? null : a.b.b;
}
}
public class Main {
public static void main(String[] args) {
A a = new A();
C c = new C();
c.c.bind(new ObjectBindingImpl(a));
a.b = new B(20); // Clearly I change the value to 20 here
System.out.println(c.c.get()); // Expected output 20 as B.b = 20 but output returned is 10.
}
}
class A {
B b = new B(10); // Assigned it value 10.
}
class B {
Integer b;
B(int b) {
this.b = b;
}
}
class C {
SimpleIntegerProperty c = new SimpleIntegerProperty();
}
根据我的理解,由于我调用了 bind(new SimpleObjectProperty(a.b)),所以每次 a.b 的值发生变化时,绑定就会失效,然后在稍后的某个时间,它使用 computeValue() 方法 impl 来分配它更新价值。
但看起来无论分配给它的第一个值是什么,即使在更改数据之后也不会改变。我在这里想念什么?我怎样才能使这个相同的例子工作?
【问题讨论】: