Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 366
davidrmcharles Avatar asked Dec 26 '22 02:12

davidrmcharles


1 Answers

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

  • Use Stage.setOnShown(). The EventHandler you pass on in this method will get called as soon as the Stage is displayed.
  • Use Platform.runLater() for requesting the initial focus.

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() );
  }
}
like image 75
eckig Avatar answered Dec 28 '22 07:12

eckig