JavaFX - 将ObjectProperty绑定到另一个ObjectProperty中的成员?

时间:2017-08-28 00:06:32

标签: java javafx properties binding

我有一个名为Tree

的班级
public class Tree
{
    private Color c;

    public Color getColor()
    {
        return c;   
    }   
}

我有ObjectProperty ...

ObjectProperty<Tree> importantTree = new SimpleObjectProperty();

我想创建另一个ObjectProperty类型Color,它始终等于importantTree.get().getColor()。每当Tree发生变化时,我都希望其他ObjectProperty变为Tree的颜色。

例如。

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.

1 个答案:

答案 0 :(得分:1)

只需使用绑定:

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.

您也可以

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

如果您愿意。