问题
I would like to make the 'folder' nodes in my JavaFX TreeView
expandable and collapsible but not selectable.
I found this discussion and looked into EventFilter
, but there does not appear to be any EventType
that corresponds with TreeView
selection changes. The second suggestion, a custom selection model, sounds like a deep dive to me. So, am I stuck allowing the selection events to trigger my listener and then sort through the trash there?
回答1:
It's a bit hacky, but I ended up doing it like this:
table.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
if (newValue != null && !newValue.isLeaf()) {
Platform.runLater(() -> table.getSelectionModel().clearSelection());
}
});
For me it was enough to just clear the selection when clicking a non-leaf node. However, it shouldn't be to hard to just reselect the oldValue
parameter, but be aware that this will fire a change event again (so does the clearSelection
call, that's why the newValue != null
check is necessary).
回答2:
There is a similar question posted here:
TreeView - Certain TreeItems are not allowed to be selected
If you use the FilteredTreeViewSelectionModel
in the answer that I posted there you can get the desired behaviour by creating a custom TreeItemSelectionFilter
and wiring everything up as follows:
MultipleSelectionModel<TreeItem<Object>> selectionModel = tree.getSelectionModel();
TreeItemSelectionFilter<Object> filter = TreeItem::isLeaf;
FilteredTreeViewSelectionModel<Object> filteredSelectionModel = new
FilteredTreeViewSelectionModel<>(tree, selectionModel, filter);
tree.setSelectionModel(filteredSelectionModel);
This will ensure that only leaf-nodes can be selected as you require.
来源:https://stackoverflow.com/questions/28999674/how-to-make-certain-javafx-treeview-nodes-non-selectable