Make JavaFX wait and continue with code

The JavaFX animations are probably the way to go, but the “thread philosophy” in JavaFX isn’t hard to work with if you want to roll your own, or do other, more complicated things in background threads.

The following code will pause and change the value in a label (full disclosure, I’m reusing code I wrote for another question):

import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

import javax.xml.datatype.Duration;

public class DelayWithTask extends Application {

    private static Label label;

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

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Hello World!");
        label = new Label();
        label.setText("Waiting...");
        StackPane root = new StackPane();
        root.getChildren().add(label);
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();

        delay(5000, () -> label.setText("Hello World"));
    }

    public static void delay(long millis, Runnable continuation) {
      Task<Void> sleeper = new Task<Void>() {
          @Override
          protected Void call() throws Exception {
              try { Thread.sleep(millis); }
              catch (InterruptedException e) { }
              return null;
          }
      };
      sleeper.setOnSucceeded(event -> continuation.run());
      new Thread(sleeper).start();
    }
}

The basic JavaFX background tool is the Task, any JavaFX application that actually does anything will probably be littered with these all over. Learn how to use them.

Leave a Comment