且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

登录失败后如何重新打开/防止ControlsFX LoginDialog关闭?

更新时间:2023-02-16 18:53:53

您可以使用将于2015年3月发布的JDK8u40中的对话框,也可以使用ConrolsFX(openjfx-dialogs-1.0.2)中的对话框.有一个实现Dialog的代码,直到未通过身份验证,该代码才会关闭.

You can use Dialog from JDK8u40 which will be released at march 2015 or use dialogs from ConrolsFX (openjfx-dialogs-1.0.2). There is a code to implement Dialog which will not be closed until authentication is not passed.

// Create the custom dialog.
Dialog<Pair<String, String>> dialog = new Dialog<>();
dialog.setTitle("Login Dialog");
dialog.setHeaderText("Look, a Custom Login Dialog");
dialog.setGraphic(new ImageView(this.getClass().getResource("login.png").toString()));

// Set the button types.
ButtonType loginButtonType = new ButtonType("Login", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(loginButtonType, ButtonType.CANCEL);

// Create the username and password labels and fields.
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(20, 150, 10, 10));

TextField username = new TextField();
username.setPromptText("Username");
PasswordField password = new PasswordField();
password.setPromptText("Password");

grid.add(new Label("Username:"), 0, 0);
grid.add(username, 1, 0);
grid.add(new Label("Password:"), 0, 1);
grid.add(password, 1, 1);

// Enable/Disable login button depending on whether a username was entered.
Button loginButton = (Button)dialog.getDialogPane().lookupButton(loginButtonType);
loginButton.setDisable(true);
**// Prevent closing dialog if not authenticated**
loginButton.addEventFilter(ActionEvent.ACTION, (event) -> { 
  if (!authenticated()) { 
    event.consume(); 
  } 
}); 
// Do some validation (using the Java 8 lambda syntax).
username.textProperty().addListener((observable, oldValue, newValue) -> {
    loginButton.setDisable(newValue.trim().isEmpty());
});

dialog.getDialogPane().setContent(grid);

// Request focus on the username field by default.
Platform.runLater(() -> username.requestFocus());

// Convert the result to a username-password-pair when the login button is clicked.
dialog.setResultConverter(dialogButton -> {
    if (dialogButton == loginButtonType) {
        return new Pair<>(username.getText(), password.getText());
    }
    return null;
});

Optional<Pair<String, String>> result = dialog.showAndWait();

result.ifPresent(usernamePassword -> {
    System.out.println("Username=" + usernamePassword.getKey() + ", Password=" + usernamePassword.getValue());
});

此示例来自以下文章例子