How to seperate logic from controller JavaFx

烂漫一生 提交于 2020-01-17 07:07:33

问题


I've got an issue with seperating business logic from controller (apart from that how i'm validating data in my program).

Here is logic class:

public class LogInMechanism {

LogInController logInController = new LogInController();
private static int howManyAttempts=0;

public void logIn()
{
howManyAttempts++;
if(howManyAttempts <3)
{
    if(logInController.getLogInField().getText().equals("nick") && logInController.getPasswordField().getText().equals("password"))
    {
        System.out.println("Button clicked");
        try {
            Parent root = FXMLLoader.load(getClass().getResource("/fxml/MainWindow.fxml"));
            logInController.getLogInField().getScene().setRoot(root);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    else
    {
        logInController.getInvalidUserOrPasswordLabel().setText("Invalid user or password "+(3-howManyAttempts)+ " attempts left!");
        logInController.getInvalidUserOrPasswordLabel().setVisible(true);
    }
}
else
{

    logInController.getInvalidUserOrPasswordLabel().setDisable(true);
    logInController.getInvalidUserOrPasswordLabel().setText("Your program has been blocked. Please contact manager!");


}
}


}

And i want this function to be used in one of my controllers

public class LogInController {
private LogInMechanism logInMechanism = new LogInMechanism();

@FXML
private Label invalidUserOrPasswordLabel;

@FXML
private TextField logInField;

@FXML
private Button logInButton;

@FXML
private PasswordField passwordField;

@FXML
void logInButtonClicked(ActionEvent event) {
    logInMechanism.logIn();
}

@FXML
public void initialize()
{
    EventHandler<KeyEvent> handlerLambda = e ->{
        if(e.getCode()==KeyCode.ENTER)
        {
        //  logInMechanism.logIn();
        }

    };
    logInButton.addEventHandler(KeyEvent.KEY_PRESSED, handlerLambda);
}

public Label getInvalidUserOrPasswordLabel() {
    return invalidUserOrPasswordLabel;
}

public TextField getLogInField() {
    return logInField;
}

public PasswordField getPasswordField() {
    return passwordField;
}

But unfortunatelly ifter performing such code i recieve an error:

Exception in Application start method
java.lang.reflect.InvocationTargetException
Caused by: java.lang.RuntimeException: Exception in Application start method
Caused by: java.lang.StackOverflowError

The error appears at line 19 in LogInMechanism class. I'm still learning though, if you have any suggestions please share.

来源:https://stackoverflow.com/questions/44913531/how-to-seperate-logic-from-controller-javafx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!