JavaFX: Focusing a text field programmatically

I wrote a JavaFX application that will only be used with keyboard arrows. So I prevented MouseEvent from being on stage and I am listening to KeyEvents. I also turned off the focusability of all nodes:

for(Node n : children) { n.setFocusTraversable(false); 

Now I have text fields, checkboxes and buttons. I would like to change the state of my input controls (text box, check box, ..) programmatically: for example, I would like to enter a text box to change the content programmatically. So my question is: how to enter the text box without focus? Because textfield.requestFocus (); no longer works as I set false for the focustraversable property of my text box.

thanks

+8
events javafx-2 focus textfield
source share
2 answers

By

 n.setFocusTraversable(false); 

node runs without focus, and not without focus. It can still be focused, for example, with the mouse or programmatically. Since you prevented mouse events, here is another option:

 Platform.runLater(new Runnable() { @Override public void run() { textfield.requestFocus(); } }); Scene scene = new Scene(root); 

EDIT: according to the comment,
The javadoc requestFocus says:

... To be eligible for focus, the node must be part of the scene, it and all its ancestors must be visible, and this should not be turned off ....

So, this method should be called after plotting the scene as follows:

 Scene scene = new Scene(root); textfield.requestFocus(); 

However, Platform.runLater in the example above will be launched at the end after the main start() method, which ensures that the requestFocus call will be executed after plotting the scene.

There may be other reasons depending on the requestFocus implementation code.

+33
source share

set the parameter .requestFocus (); when initializing the method, start the .fxml file upload controller

 @Override public void initialize(URL url, ResourceBundle rb) { /* the field defined on .fxml document @FXML private TextField txtYear; */ txtYear.requestFocus(); } 
+1
source share

All Articles