簡體   English   中英

是否可以在JavaFX中創建動態Bindings.OR?

[英]Is it possible to create dynamic Bindings.OR in JavaFX?

讓我們考慮以下情況。 有一個Pane parentPane ,還有一個Pane parentPane Pane firstChildPane, secondChildPane, thirdChildPane ... 子窗格將添加到父窗格。 考慮到可以動態地添加和刪除子窗格而沒有任何限制和順序的情況下,如何才能僅在可見子窗格的情況下使parentPane可見。 當然childPane的可見狀態也可以隨時更改。 是否可以創建動態Bindings.OR,以便可以動態向其添加/刪除子可見屬性? 如果是,那怎么辦? 如果沒有,那么在這種情況下使用什么解決方案?

您可以按照以下方式嘗試操作:

// 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

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM