Search code examples
javajavafxtreeview

Set selected TreeItem in TreeView


I have a TreeView that is inside a GridPane. A certain function requires the user to select a TreeItem and click on button on the screen. After the function associated with the button is completed, I want the focus to go back to the TreeItem that was previously selected in the TreeView.

At the end of the button action, I have:

TreeItem<String> selectedItem = [TreeItem that was last selected]

How can I give focus back to the TreeView with selectedItem highlighted?

Neither the TreeView or TreeItem have a setSelected method I can use.


Solution

  • To select an item:

    TreeView treeView = ... ; // initialize this
    TreeItem treeItem = ... ; // initialize this, too
    MultipleSelectionModel msm = treeView.getSelectionModel();
    
    // This line is the not-so-clearly documented magic.
    int row = treeView.getRow( treeItem );
    
    // Now the row can be selected.
    msm.select( row );
    

    That is, get the row of the treeItem from its treeView, then pass that row into the treeView's selection model.

    Aside, the TreeView API could be improved to delegate for a single tree item:

    treeView.select( treeItem );
    

    Unfortunately, no such method exists.