Reputation: 1894
I want to set focus to a specific node in the content of a Tab. I added a ChangeListener to selectedItem property as follows (assume that the class contains a field named secondNode of type Node):
tabPane.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Tab>() {
@Override
public void changed(ObservableValue<? extends Tab> observable, Tab oldValue, Tab newValue) {
if (newValue != null) {
Platform.runLater(new Runnable() {
@Override
public void run() {
secondNode.requestFocus();
}
});
}
}
});
However, this does not work. I assume the reason is because TabPane performs some additional actions, which affect focus, after the new tab has been selected (but, looking through TabPane source code, I can't figure out what). If I single-step through this code in a debugger, it works as expected, so it appears to be a race condition. If this is so, how can this be resolved?
Upvotes: 4
Views: 1608
Reputation: 2154
You could try replacing the Runnable with a Task:
new Thread( new Task<Void>()
{
@Override
public Void call() throws Exception // This is NOT on FX thread
{
Thread.sleep(100);
return null;
}
@Override
public void succeeded() // This is called on FX thread.
{
secondNode.requestFocus();
}
}).start();
Upvotes: 1