简体   繁体   中英

Printing a different text after waiting a certain period of time (JavaFX)

I print some text and then I want to wait 2 seconds and print something else on the screen. I Googled around and everything seems like overkill using threads and invoking methods. I am sure there's a simpler way.

Here's what I tried:

public class Test extends Application {

    @Override
    public void start(Stage primaryStage) {

        GridPane root = new GridPane();
        primaryStage.setScene(new Scene(root, 1000, 1000));
        Text text = new Text("bla");




        root.getChildren().addAll(text);        
        primaryStage.show();

        try {
            Thread.sleep(2000);
        }
        catch(Exception e) {

        }
        root = new GridPane();
        root.getChildren().addAll(new Text("adsasd"));
        primaryStage.show();

    }


    public static void main(String[] args) {
        Test.launch();
    }
}

JavaFX, like nearly all user interface toolkits, runs on a single thread. Your sleep call blocks that thread. While the method is sleeping, no windows are shown, nothing is redrawn, and no user input is processed.

In short, you cannot sleep or cause any other significant delays in a method called by JavaFX.

JavaFX supplies lots of classes in the javafx.animation package which will properly enact delays. In your case, a PauseTransition will work.

PauseTransition delay = new PauseTransition(Duration.seconds(2));
delay.setOnFinished(e -> root.getChildren().add(new Text("adsasd")));
delay.play();

(You can also create a Thread, ScheduledExecutorService, delayed CompletableFuture, or java.util.Timer, but those will require the use of Platform.runLater . Plus, you have indicated that you're trying to avoid threads. PauseTransition is probably the most straightforward solution.)

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