Programmatically edit TreeView/TreeItem

为君一笑 提交于 2019-11-29 15:24:05

TreeCells (that is their content and binding to the treeItem) are updated lazily in a layout pass, that is very "late" when the next pulse is fired. A Platform.runLater(..) or any hard-coded delay may happen before or after that pulse, that's (probably) why both seem to work or not spuriously.

So another whacky hack is to manually force a re-layout on the tree after having added a new item and before programatically starting an edit:

root.getChildren().add(newItem);
tree.layout();
tree.edit(newItem);

Needless to say, that this shouldn't be necessary - the current behaviour is a severe bug and must be fixed at once (... meaning ... jdk 9)

It seems, the treeView is needing more time to do its internal calculations before the newly added item got reflected to it. To determine exactly which calculations are causing the problem, one need to dig the source code and see what is going on under the hood.

The workaround is to force treeView do its calculation immediately,

@FXML
public void createItem() throws InterruptedException {
    TreeItem<String> newItem = new TreeItem<>();
    newItem.setValue("Item " + tree.getExpandedItemCount());

    tree.getRoot().getChildren().add(newItem);

    // Trigger whatever calculations there internally
    TreeItem<String> r = tree.getRoot();
    tree.setRoot( null );
    tree.setRoot( r );

    tree.requestFocus();
    tree.getSelectionModel().select(newItem);
    tree.edit(newItem);
}

This workaround was found totally intuitively based on other bugs in JavaFX ;-)


Alternatively, since Platform.runlaters's postponed time is obviously not enough, you may use PauseTransition to increase the time needed:

PauseTransition p = new PauseTransition( Duration.millis( 100 ) );
p.setOnFinished( new EventHandler<ActionEvent>()
{
    @Override
    public void handle( ActionEvent event )
    {
        tree.edit( newItem );
    }
} );
p.play();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!