Hatefiend Hatefiend - 2 months ago 17
Java Question

JavaFX - Bind ObjectProperty to member inside another ObjectProperty?

I have a class called

Tree


public class Tree
{
private Color c;

public Color getColor()
{
return c;
}
}


I have an
ObjectProperty
...

ObjectProperty<Tree> importantTree = new SimpleObjectProperty();


I want to make another
ObjectProperty
of type
Color
that is always equal to
importantTree.get().getColor()
. Whenever the Tree changes, I want the other ObjectProperty to change to that Tree's color.

For example.

ObjectProperty<Tree> importantTree = new SimpleObjectProperty();
ObjectProperty<Color> importantTreesColor = ...


Tree a = new Tree(Color.RED);
Tree b = new Tree(Color.GREEN);

importantTree.set(a);
System.out.println(importantTreesColor.get()); // This should print RED.

importantTree.set(b);
System.out.println(importantTreesColor.get()); // This should print GREEN.

Answer Source

Just use a binding:

ObjectProperty<Tree> importantTree = new SimpleObjectProperty();
Binding<Color> importantTreesColor = Bindings.createObjectBinding(() -> 
    importantTree.get() == null ? null : importantTree.get().getColor(),
    importantTree);

Tree a = new Tree(Color.RED);
Tree b = new Tree(Color.GREEN);

importantTree.set(a);
System.out.println(importantTreesColor.getValue()); // Prints RED.

importantTree.set(b);
System.out.println(importantTreesColor.getValue()); // Prints GREEN.

You can also do

Binding<Color> importantTreesColor = new ObjectBinding<Color>() {
    { bind(importantTree); }
    @Override
    protected Color computeValue() {
        return importantTree.get()==null ? null : importantTree.get().getColor();
    }
};

if you prefer.