Set selected TreeItem in TreeView

后端 未结 3 1458
长情又很酷
长情又很酷 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 );
    }
    
    0 讨论(0)
  • 2021-01-21 11:37

    TreeView.getSelectionModel() offers:

    • getSelectedItem
    • setSelectedItem

    These are protected methods, so consider using select.

    0 讨论(0)
  • 2021-01-21 11:40

    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.

    0 讨论(0)
提交回复
热议问题