是否可以在JavaFX中创建动态Bindings.OR? [英] Is it possible to create dynamic Bindings.OR in JavaFX?

查看:46
本文介绍了是否可以在JavaFX中创建动态Bindings.OR?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑以下情况.有一个 Pane parentPane ,有一个 Pane firstChildPane,secondChildPane,thirdChildPane ... .子窗格将添加到父窗格.考虑到可以动态地添加和删除子窗格而没有任何限制和顺序的情况下,如何才能仅在可见子窗格的情况下使parentPane可见.当然childPane的可见状态也可以随时更改.是否可以创建动态Bindings.OR,以便可以动态向其添加子可见属性或从中删除子可见属性?如果是,那怎么办?如果没有,那么在这种情况下使用什么解决方案?

Lets consider the following situation. There is a Pane parentPane and there are Pane firstChildPane, secondChildPane, thirdChildPane .... Child panes are added to parent pane. How can I make parentPane be visible only in that case if any of child pane is visible taking into consideration that child panes can be added and removed dynamically without any limit and in any order. Of course childPane visible state can be also changed any time. Is it possible to create dynamic Bindings.OR in order I could add/remove child visible property to/from it dynamically? If yes, then how? If not, then what solutions are used in such cases?

推荐答案

您可以尝试以下方法:

// list that fires updates if any members change visibility:
ObservableList<Node> children = 
    FXCollections.observableArrayList(n -> new Observable[] {n.visibleProperty()});
// make the new list always contain the same elements as the pane's child list:
Bindings.bindContent(children, parentPane.getChildren());
// filter for visible nodes:
ObservableList<Node> visibleChildren = children.filter(Node::isVisible);
// and now see if it's empty:
BooleanBinding someVisibleChildren = Bindings.isNotEmpty(visibleChildren);
// finally:
parentPane.visibleProperty().bind(someVisibleChildren);

另一种方法是直接创建自己的 BooleanBinding :

Another approach is to create your own BooleanBinding directly:

Pane parentPane = ... ;

BooleanBinding someVisibleChildren = new BooleanBinding() {


    {
        parentPane.getChildren().forEach(n -> bind(n.visibleProperty()));

        parentPane.getChildren().addListener((Change<? extends Node> c) -> {
            while (c.next()) {
               c.getAddedSubList().forEach(n -> bind(n.visibleProperty()));
               c.getRemoved().forEach(n -> unbind(n.visibleProperty())) ;
            }
        });

        bind(parentPane.getChildren());
    }

    @Override
    public boolean computeValue() {
        return parentPane.getChildren().stream()
            .filter(Node::isVisible)
            .findAny()
            .isPresent();
    }
}

parentPane.visibleProperty().bind(someVisibleChildren);

这篇关于是否可以在JavaFX中创建动态Bindings.OR?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆