1

In my application, the first I do is request the user to login using the controlsFX LoginDialog. If the login is successful, I display the application, however if it fails the login window will close.

I would rather the login window stay open to allow the user to attempt to login again.

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

}

If the login is unsuccessful, the dialog closes - which requires the user to reopen the application.

1
  • I was unable to make this work - so I created a custom stage to handle the login, rather than using a dialog. If someone has a better way, I would really appreciate it. Feb 9, 2015 at 15:18

2 Answers 2

3

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

this example was given from this article where you can find many useful examples

1
  • Thanks! I didn't think to add an event filter. Mar 2, 2015 at 14:28
0

Try this:

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


}

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.