Search code examples
javajavafxwaitsleeppause

JavaFX Thread.Sleep() or pause() in ActionEvent


I'm new at JavaFX and I was trying whenever I press the button, first, it shows some info on a label, then change the scene. Everything is OK actually, but I just couldn't find how to wait for a specific amount of time before the change scene.

I tried with Thread.sleep() like this: (its wait properly, but somehow it doesn't change the text of the label)

    @FXML
public void pressButton(ActionEvent event) throws IOException, InterruptedException {
    user = new User(inUsername.getText(),inPassword.getText());
    lLeftBottom.setText(user.getUserInfo());
    Thread.sleep(2000);
    changeScene2(event);
}

(edit, thanks to Slaw for solution about the pause()'s actionEvent problem)

and also I try about JavaFX's pause method, but it doesn't wait, still jumping the other scene immediately

    @FXML
public void pressButton(ActionEvent event) throws IOException, InterruptedException {
    user = new User(inUsername.getText(),inPassword.getText());
    PauseTransition pause = new PauseTransition(Duration.seconds(3));
    pause.setOnFinished(e ->{
        lLeftBottom.setText(user.getUserInfo());
    });
    pause.play();
    changeScene2(event);
}

How can I make this delay ?


Solution

  • You've used the PauseTransition backwards. If you want to change the scene after the pause, that is the part that needs to be in your onFinished event handler:

    @FXML
    public void pressButton(ActionEvent event) throws IOException, InterruptedException {
        user = new User(inUsername.getText(),inPassword.getText());
        PauseTransition pause = new PauseTransition(Duration.seconds(3));
        pause.setOnFinished(e ->{
            changeScene2(event);
        });
        lLeftBottom.setText(user.getUserInfo());
        pause.play();
    }