I am very confused as how to bind an ObjectProperty to another Object using Object binding. From what I have read & understood in javaFX documentations, this MCVE should output 20, but it is not working. Output is coming to 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();
}
As per my understanding, since I have called bind(new SimpleObjectProperty(a.b)) so everytime the value of a.b changes, the binding is invalidated, and then sometime later, it uses the computeValue() method impl to assign it updated value.
But it appears that whatever the first value assigned to it was does not change even after changing the data. What am I missing here? How can I make this same example work?