我有一个名为Tree
的类
public class Tree
{
private Color c;
public Color getColor()
{
return c;
}
}
我有一个ObjectProperty
...
ObjectProperty<Tree> importantTree = new SimpleObjectProperty();
我想创建另一个 Color
类型的 ObjectProperty
,它始终等于 importantTree.get().getColor()
。每当树发生变化时,我希望其他 ObjectProperty 更改为该树的颜色。
例如。
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.
最佳答案
只需使用绑定(bind):
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();
}
};
如果你愿意的话。
关于JavaFX - 将 ObjectProperty 绑定(bind)到另一个 ObjectProperty 内的成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45910375/