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

cbm64 :

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!

M. S. :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=395065&siteId=1