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
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 );
}
TreeView.getSelectionModel() offers:
These are protected methods, so consider using select.
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.