Issue
I am using Stage
to create a simple dialog that contains a Label
, a TextField
and two Button
s, 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:
- Use
Stage.setOnShown()
. TheEventHandler
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() );
}
}
Answered By - eckig
Answer Checked By - Clifford M. (JavaFixing Volunteer)