john
john

Reputation: 1747

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.

Upvotes: 5

Views: 16304

Answers (3)

eckig
eckig

Reputation: 11134

TreeView.getSelectionModel() offers:

These are protected methods, so consider using select.

Upvotes: 6

mike rodent
mike rodent

Reputation: 15633

Just to expand (...) on the comment made by malamut to the chosen answer, and also to clarify something:

Actually, you do not have to do two operations (find row, then select row). This works fine:

tableView.getSelectionModel().select( treeItem );

But, with this, or any other method to set selection programmatically, this will simply fail if the tree item is not showing. "Showing" is not the same as visible: a node can be showing but not be visible, for example with a ScrollPane, where the part of the tree in question has been scrolled out of view.

"Showing" means that all ancestors of the TreeItem in question, up to and including the root TreeItem, are expanded. There appears to be no built-in method to accomplish this currently (JavaFX 11). So you'd typically do something like this before attempting programmatic selection:

for( TreeItem ti = treeItemToBeSelected; ti.getParent() != null; ti = ti.getParent() ){
    ti.getParent().setExpanded( true );
}

Upvotes: 1

Dave Jarvis
Dave Jarvis

Reputation: 31171

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.

Upvotes: 10

Related Questions