Set selected TreeItem in TreeView

后端 未结 3 1464
长情又很酷
长情又很酷 2021-01-21 11:11

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

3条回答
  •  情话喂你
    2021-01-21 11:34

    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 );
    }
    

提交回复
热议问题