简体   繁体   中英

Disable Context Menu on a a child of a root JavaFX TreeView<Label> with TreeItem<Label>

A JavaFX 14 Treview with TreeItem<Label> in this structure;

  • Root
    • Group
      • Child
    • Group
      • Child
      • Child

I have attached a ContextMenu to the Label at the Root to add and remove Groups. And I am able to disable the Remove Groups when there are no groups using;

removeGroupMenuItem.disableProperty().bind(Bindings.isEmpty(treeView.getRoot().getChildren()));

However, I have now attached ContextMenu to the Label of each Group that allows adding a child or removing all children. My question is, how can I disable the Remove All Children MenuItem if one or more Groups are selected.

I have tried which does not work;

removeAllChildrenMenuItem.disableProperty().bind(Bindings.createBooleanBinding(() -> treeView.getSelectionModel().getSelectedItems().stream().flatMap(f -> f.getChildren().stream()).collect(Collectors.toList()).size() == 0, treeView.selectionModelProperty()));

Any thought welcome!

Your Binding will not be invalidated because your code waits for the SelectionModel property to be changed, not the selected items:

Bindings.createBooleanBinding(() -> treeView.getSelectionModel().getSelectedItems().stream().flatMap(f -> f.getChildren().stream()).collect(Collectors.toList()).size() == 0, treeView.selectionModelProperty());

You can fix that by changing the dependencies of the binding:

Bindings.createBooleanBinding(() -> treeView.getSelectionModel().getSelectedItems().stream().flatMap(f -> f.getChildren().stream()).collect(Collectors.toList()).size() == 0, treeView.getSelectionModel().getSelectedItems());

Note: If you change the tree's selection model by using treeView.setSelectionModel(...) anywhere else in your code, you have to rebind disable property again. If this is a common thing in your code, you can add a dependency to the selection model so the code become like this:

Bindings.createBooleanBinding(() -> {...}, treeView.selectionModelProperty(), treeView.getSelectionModel().getSelectedItems());

That means, recalculate the value whenever the selection model or the selected items change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM