Edit #2: Since it looks like a bug i already posted a bug report in the javaFx-jira. You have to have an account to have access to the issue. I will keep th
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();