How to prevent TreeItem selection?

2019-07-11 05:50发布

问题:

I'm working with a TreeTableView (JavaFX 8). There are some tree nodes, which have to be disabled for selection. I had tried the selection event, but it doesn't work. Please find the below code for more information.

treeTableView.getSelectionModel().selectedItemProperty().addListener(
                (observable, oldValue, newValue) ->
    {
        // utility node
        if(newValue.getValue() instanceof UtilityRoot )
        {
            return;
        }  
    }
);

How can I prevent some TreeItems from any mouse and keyboard selection?

回答1:

What you try to achieve cannot work as it simply adds a listener to be notified any time the selected item changes which is already too late in your case as you want to prevent the selection which happens before calling the listeners.

By default you can specify if you want the SINGLE or MULTUPLE selection mode using treeTableView.getSelectionModel().setSelectionMode(selectionMode) and if you want to allow cell selection using treeeTableView.getSelectionModel().setCellSelectionEnabled(enabled).

  • SelectionMode.SINGLE and cell selection enabled: Enables selection of a single cell in the table.
  • SelectionMode.SINGLE and cell selection disabled: Enables selection of a single row in the table.
  • SelectionMode. MULTUPLE and cell selection enabled: Enables selection of several cells in several rows.
  • SelectionMode. MULTUPLE and cell selection disabled: Enables selection of several rows in the table.

If it is not good enough for you, you will need to implement your own TreeTableViewSelectionModel and set it using setSelectionModel(TreeTableView.TreeTableViewSelectionModel<S> value).