0

I have this class that generates a Alert Dialog with a field to enter a password, and want to activate the OK button when pressing Enter on the password field.

public class PasswordDialog extends Dialog<String> {
    private PasswordField passwordField;

    public PasswordDialog(boolean usuario) {
        setTitle("Senha");
        if (usuario == true){
            setHeaderText("Por favor insira a senha do usuário.");
        }else{
            setHeaderText("Por favor insira a senha do administrador.");
        }

        ButtonType passwordButtonType = new ButtonType("OK", ButtonData.OK_DONE);
        getDialogPane().getButtonTypes().addAll(passwordButtonType, ButtonType.CANCEL);

        passwordField = new PasswordField();
        passwordField.setPromptText("Password");

        HBox hBox = new HBox();
        hBox.getChildren().add(passwordField);
        hBox.setPadding(new Insets(20));

        HBox.setHgrow(passwordField, Priority.ALWAYS);

        getDialogPane().setContent(hBox);

        Platform.runLater(() -> passwordField.requestFocus());

        setResultConverter(dialogButton -> {
            if (dialogButton == passwordButtonType) {
                return passwordField.getText();
            }
            return null;
        });
    }

    public PasswordField getPasswordField() {
        return passwordField;
    }
}
Pagbo
  • 691
  • 5
  • 13
  • 2
    Possible duplicate of [How to use KeyEvent in JavaFX project?](https://stackoverflow.com/questions/27982895/how-to-use-keyevent-in-javafx-project) – Gnas Dec 18 '18 at 15:43
  • Possible duplicate of [How do I pick up the Enter Key being pressed in JavaFX2?](https://stackoverflow.com/questions/13880638/how-do-i-pick-up-the-enter-key-being-pressed-in-javafx2) – Pagbo Dec 18 '18 at 15:47

1 Answers1

0

Actually this should happen by default (at least that's the behaviour on JavaFX 11/Win 10), but you can also close the Dialog yourself by calling setResult and close.

Example closing on arrow keys:

// in constructor
passwordField.setOnKeyPressed(evt -> {
    if (evt.getCode().isArrowKey()) {
        setResult(passwordField.getText());
        close();
    }
});

For closing on pressing enter, use the onAction event of the PasswordField:

// in constructor
passwordField.setOnAction(evt -> {
    setResult(passwordField.getText());
    close();
});

For more complicated behaviour of the resultConverter, you could also use it for setting the result to avoid duplicate code:

setResult(getResultConverter().call(passwordButtonType));
fabian
  • 80,457
  • 12
  • 86
  • 114