加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

如何将属性绑定到列表属性中的对象的属性?

发布时间:2020-12-15 04:36:36 所属栏目:Java 来源:网络整理
导读:我有这些课程: class Parent { BooleanProperty total = new SimpleBooleanProperty(); SimpleListPropertyChild children = new SimpleListProperty(FXCollections.observableArrayList());}class Child { BooleanProperty single = new SimpleBooleanProp
我有这些课程:

class Parent {

    BooleanProperty total = new SimpleBooleanProperty();
    SimpleListProperty<Child> children = new SimpleListProperty<>(FXCollections.observableArrayList());
}

class Child {

    BooleanProperty single = new SimpleBooleanProperty();
}

我想要的是,当且仅当所有孩子的单身都是假的时候,总数将是假的.换句话说,当且仅当有一个孩子单身为真时,则总数为真.

我想出了这个绑定

total.bind(Bindings.createBooleanBinding(() -> {
    return children.stream().filter(c -> c.isSingle()).findAny().isPresent();
},children.stream().map(c -> c.single).collect(Collectors.toCollection(FXCollections::observableArrayList))));

这是最好的方法吗?

我也应该只读全部读取因为写入绑定属性会抛出异常吗?

解决方法

显式绑定到每个子单个属性的一个可能问题是,在调用total.bind(…)语句时会产生这些绑定.因此,如果随后将新的Child对象添加到列表中,则不会观察到这些子对象的单个属性,并且如果它们发生更改,则绑定将不会失效.同样,如果从列表中删除子项,则其单个属性将不会被绑定.

作为替代方案,您可以使用extractor创建列表.请注意,对于大多数用例,您不需要ListProperty:只需直接使用ObservableList就足够了.所以你可以做到

ObservableList<Child> children = 
    FXCollections.observableArrayList(c -> new Observable[]{c.singleProperty()});

如果任何元素单个属性失效(以及在列表中添加元素时),此列表现在将触发更新通知(并变为无效).换句话说,列表本身会观察每个子节点的单个属性,如果任何子节点的单个属性变为无效,则列表将变为无效(导致绑定到它的任何内容无效).该列表还确保在将子项添加到列表时观察新子项的单个属性,并在从列表中删除子项时停止观察它们.

那你就需要了

total.bind(Bindings.createBooleanBinding(() -> 
    children.stream().anyMatch(Child::isSingle),children);

最后,考虑使用ReadOnlyBooleanWrapper以将属性公开为只读.这是整个事物的正确封装版本:

public class Parent {

    private ReadOnlyBooleanWrapper total = new ReadOnlyBooleanWrapper();
    private ObservableList<Child> children = 
        FXCollections.observableArrayList(c -> new Observable[] {c.singleProperty()});

    public Parent() {
        total.bind(Bindings.createBooleanBinding(() -> 
            children.stream().anyMatch(Child::isSingle),children);
    }

    public ReadOnlyBooleanProperty totalProperty() {
        return total.getReadOnlyProperty();
    }

    public ObservableList<Child> getChildren() {
        return children ;
    }

}

public class Child {
    private final BooleanProperty single = new SimpleBooleanProperty();

    public BooleanProperty singleProperty() {
        return single ;
    }

    public final boolean isSingle() {
        return singleProperty().get();
    }

    public final void setSingle(boolean single) {
        singleProperty().set(single);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读