【发布时间】:2017-10-11 10:22:15
【问题描述】:
我有一个 JavaFX 应用程序,它最初会显示一个登录对话框,供用户输入用户名和密码。请参阅下面的源代码。
如果用户点击“连接”按钮,应用程序将使用输入的用户名和密码进行登录,隐藏登录对话框,然后显示主窗口。
如果用户单击“退出”按钮或“X”关闭按钮,将显示警报以获取用户的确认。如果用户确认,则应用程序退出。
我的问题是当用户在登录对话框显示时按下 Escape 键时会发生什么。按下此键时,将显示退出确认警报,然后立即关闭。所以我们看到的是退出确认对话框,只要按下 Escape 键就会立即出现。
为什么会这样?
我希望按 Escape 键相当于单击“退出”或“X”按钮。也就是说,当按下 Escape 键时,会显示退出确认对话框。
或者,是否可以完全禁用 Escape 键?
提前致谢。
public class TestApp extends Application {
private Stage primaryStage;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
this.primaryStage = stage;
HBox pane = new HBox();
pane.setAlignment(Pos.CENTER);
Scene scene = new Scene(pane, 300, 300);
stage.setScene(scene);
showLoginDialog();
}
public void showLoginDialog() {
Dialog<String> loginDialog = new Dialog<>();
loginDialog.setTitle("Login");
loginDialog.setHeaderText("Enter User Name and Password to login.");
loginDialog.setResizable(false);
Label userNameLabel = new Label("User Name:");
Label passwordLabel = new Label("Password:");
TextField userNameField = new TextField();
userNameField.setMaxWidth(Double.MAX_VALUE);
PasswordField passwordField = new PasswordField();
passwordField.setMaxWidth(Double.MAX_VALUE);
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(20, 35, 20, 35));
grid.add(userNameLabel, 1, 1);
grid.add(userNameField, 2, 1);
grid.add(passwordLabel, 1, 2);
grid.add(passwordField, 2, 2);
loginDialog.getDialogPane().setContent(grid);
loginDialog.getDialogPane().getButtonTypes().add(ButtonType.OK);
loginDialog.getDialogPane().getButtonTypes().add(ButtonType.CANCEL);
Button connectButton = (Button) loginDialog.getDialogPane().lookupButton(ButtonType.OK);
connectButton.setText("Connect");
connectButton.addEventFilter(ActionEvent.ACTION, event -> {
// perform login here
loginDialog.hide();
primaryStage.show();
event.consume();
});
Button exitButton = (Button) loginDialog.getDialogPane().lookupButton(ButtonType.CANCEL);
exitButton.setText("Exit");
exitButton.addEventFilter(ActionEvent.ACTION, event -> {
handleExit();
event.consume();
});
Stage stage = (Stage) loginDialog.getDialogPane().getScene().getWindow();
stage.setOnCloseRequest(event -> {
handleExit();
event.consume();
});
stage.show();
}
private void handleExit() {
Alert alert = new Alert(AlertType.CONFIRMATION, "", ButtonType.YES, ButtonType.NO);
alert.setHeaderText("Confirm exit?");
alert.resultProperty().addListener((observable, previous, current) -> {
if (current == ButtonType.YES) {
System.exit(1);
}
});
alert.show();
}
}
【问题讨论】:
-
上面的代码对我来说很好用。退出按钮只显示确认对话框,仅此而已。
-
当我按下退出键时,确认提示出现然后立即关闭。
-
这对我来说并没有发生。很奇怪......你确定你正在运行上面的代码吗?你的 jdk 版本是多少?
-
我正在使用 JFK1.8。
-
我刚试过你的代码,它也对我有用。