我有一个此类,该类会生成一个带有用于输入密码的字段的警报对话框,并且想在按密码字段上的 Enter 时激活“确定”按钮。
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;
}
}
答案 0 :(得分:0)
实际上,默认情况下应该发生这种情况(至少是JavaFX 11 / Win 10上的行为),但是您也可以通过调用Dialog
和setResult
来自己关闭close
。 / p>
以箭头键关闭的示例:
// in constructor
passwordField.setOnKeyPressed(evt -> {
if (evt.getCode().isArrowKey()) {
setResult(passwordField.getText());
close();
}
});
要在按下Enter键时关闭,请使用onAction
的{{1}}事件:
PasswordField
对于// in constructor
passwordField.setOnAction(evt -> {
setResult(passwordField.getText());
close();
});
的更复杂的行为,您还可以使用它来设置结果以避免重复的代码:
resultConverter