简体   繁体   中英

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?

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

About your first question: Try using try catch. Worked out for me.

public static void main(String[] args) {
    System.out.println("test1");
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("test2");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM