我有一个名为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.
答案 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();
}
};
如果您愿意。