Skip to content
Advertisement

RequestFocus in TextField doesn’t work

I use JavaFX 2.1 and I created GUI using FXML, in the controller of this GUI I added myTextField.requestFocus();.

But I always get the focus in the other control.

Advertisement

Answer

At the time of initialize() controls are not yet ready to handle focus.

You can try next trick:

JavaScript

For tricky complex applications (like Pavel_K has in the comments) you may want to repeat this routine several times and call method line next one:

JavaScript

Note this is the undocumented approach and it may be wise to add a limit for repetitions to avoid endless loop if something changed or broke in future Java releases. Better to lose focus than a whole app. 🙂


Example with the described threshold:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement