Search code examples
dialogjavafxjavafx-8

JavaFX8: How do I set the initially focused control in a Stage?


I am using Stage to create a simple dialog that contains a Label, a TextField and two Buttons, namely OK and Cancel.

When my application runs on Java7, the one and only TextField control has keyboard focus implicitly. This is not the case on Java8. On Java8, the user must click the TextField with the mouse to begin typing into it.

It seems as if I will have to extend Stage and override Stage.showAndWait() to request focus for my TextField control.


Solution

  • Invoke Node.requestFocus() in one of the following ways:

    Here's an example (JavaFX 11):

    import javafx.application.Platform;
    import javafx.scene.control.Dialog;
    import javafx.scene.control.TextField;
    import javafx.scene.layout.StackPane;
    import javafx.stage.Window;
    
    public final class CustomDialog extends Dialog<String> {
      private final TextField mField = new TextField();
    
      private CustomDialog( final Window owner ) {
        super( owner, "My Dialog" );
    
        final var contentPane = new StackPane();
        contentPane.getChildren().add( mField );
        
        final var dialogPane = getDialogPane();
        dialogPane.setCOntent( contentPane );
    
        Platform.runLater( () -> mField.requestFocus() );
      }
    }