1

在我的应用程序中,我首先要求用户使用 controlsFX LoginDialog 登录。如果登录成功,我会显示应用程序,但是如果登录失败,登录窗口将关闭。

我宁愿登录窗口保持打开状态以允许用户再次尝试登录。

public void start(Stage stage) throws Exception {

    LoginDialog ld = new LoginDialog(new Pair<String, String>("", ""), new Callback<Pair<String,String>, Void>() {
        @Override
        public Void call(Pair<String, String> info) {
            boolean success = login(info.getKey(), info.getValue());
            if(success){
               openDriverWindow(stage);
            }else {
               //Display error message      
            }
            return null;
        }
    });
    ld.show();

}

如果登录不成功,对话框将关闭——这需要用户重新打开应用程序。

4

2 回答 2

3

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

// 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());
});

这个例子是从这篇文章中给出的,你可以在其中找到许多有用的例子

于 2015-03-01T06:50:52.063 回答
0

尝试这个:

public class Main  extends Application{


private boolean login(String key, String value){
    Pair loginData = new Pair<String, String>("test", "test");

    if (loginData.getKey().equals(key) && loginData.getValue().equals(value)) {
        return true;
    }
    else {
        //Вывести Alert.
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                try {
                    Alert alert = new Alert(Alert.AlertType.ERROR, "Вы ввели неправильное имя или пароль");
                    alert.setTitle("Error");
                    alert.showAndWait();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        return false;
    }
}

@Override
public void start(Stage primaryStage) throws Exception {
    primaryStage.setTitle("Terminal Kuban-electro");

     getLogin(primaryStage);
        primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
            @Override
            public void handle(WindowEvent t) {
                System.exit(0);
            }
        });




}


private void getLogin(Stage primaryStage){
    LoginDialog ld = new LoginDialog(new Pair<String, String>("", ""), new Callback<Pair<String, String>, Void>() {
        @Override
        public Void call(Pair<String, String> info) {
            boolean success = login(info.getKey(), info.getValue());
            if (success) {
                Scene scene = null;
                try {
                    scene = new Scene(FXMLLoader.load(getClass().getClassLoader().getResource("fxml/main.fxml")));
                    primaryStage.setScene(scene);
                    primaryStage.show();
                } catch (IOException e) {

                }
            } else {
               getLogin(primaryStage);
            }
            return null;
        }
    });
    ld.setHeaderText("Введите имя пользователя и пароль");
    ld.setTitle("Авторизация");
    ld.show();

}


public static void main(String[] args) throws MalformedURLException {
    //Инициализация формы в потоке
    Thread myThready = new Thread(() -> {
        launch(args);
    });
    myThready.start();


}

}

于 2017-03-19T12:39:30.923 回答