gpt4 book ai didi

JavaFX - 将 ObjectProperty 绑定(bind)到另一个 ObjectProperty 内的成员?

转载 作者:行者123 更新时间:2023-12-02 12:19:13 25 4
gpt4 key购买 nike

我有一个名为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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com