JavaFX button reacting on second click not first

前端 未结 1 356
傲寒
傲寒 2020-12-18 17:15

I am trying to create my very first application in JavaFX and I have a problem with Button that calls a method (for example to open another window) - I always have to click

相关标签:
1条回答
  • 2020-12-18 17:40

    Most likely you have the following in your FXML:

    <Button fx:id="forgot" onAction="#forgetPasswordClicked" />
    

    This makes your button forgot call your method forgetPasswordClicked(). But instead of defining your logic to be executed when your button is clicked, the first time you say: "When this button is clicked, place an action event on my button which will call setUpWindow()"

    forgot.setOnAction(e -> ForgotPassword.setUpWindow());
    

    Therefore, your first click "sets up" the logic of your button. The second click, actually executes it. To solve this, either immediately use your logic as such:

    public void forgetPasswordClicked() {
        ForgotPassword.setUpWindow();
    }
    

    or don't define the method to be called in your fxml, and move the initialization of your button (setting the action listener) to your initialization as following:

    public class ControllerSignIn implements Initializable {
        @FXML
        private Button forgot;
        @FXML
        private Button back;
    
        @Override
        public void initialize(URL location, ResourceBundle resources) {
            forgot.setOnAction(e -> ForgotPassword.setUpWindow());
            back.setOnAction(e -> ForgotPassword.closeWindow());
        }
    }
    

    This is also why your signInClicked() method works from the first click, because it actually executes the logic instead of setting up the handler first.

    0 讨论(0)
提交回复
热议问题