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.

11/14/2014 11:45:16 AM

Accepted Answer

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. 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: treeItem );

Unfortunately, no such method exists.

11/7/2016 1:39:40 AM

I think TreeView.getSelectionModel() is your friend.

It offers:

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow