0

Given:

    BorderPane root = new BorderPane();
    GridPane block = new GridPane();
    block.addRow(0, new Text("HELLO"));

    ScheduledExecutorService someScheduler = Executors.newScheduledThreadPool(4);
    someScheduler.schedule(() -> {
        System.out.println("IN");
        block.addRow(1, new Text("WORLD"));
        System.out.println("OUT");
    }, 2, TimeUnit.SECONDS);

    root.setCenter(block);

    Scene scene = new Scene(root, 1280, 720);
    primaryStage.setScene(scene);
    primaryStage.show();

Shouldn't the GridPane add a row after 2 seconds? The Output reaches the IN but never the OUT. Can someone explain this behaviour to me?

P. Daimaou
  • 51
  • 5
  • 4
    `block.addRow` is most likely throwing an exception because you are attempting to update the UI from a background thread. You're only allowed to update the UI from the _JavaFX Application Thread_: see [`Platform.runLater`](https://docs.oracle.com/javase/10/docs/api/javafx/application/Platform.html#runLater(java.lang.Runnable)). However, don't use a thread pool for this when a [`PauseTransition`](https://docs.oracle.com/javase/10/docs/api/javafx/animation/PauseTransition.html) or [`Timeline`](https://docs.oracle.com/javase/10/docs/api/javafx/animation/Timeline.html) would be sufficient. – Slaw Aug 22 '18 at 17:55
  • 1
    See https://stackoverflow.com/questions/30543619/how-to-use-pausetransition-method-in-javafx – Slaw Aug 22 '18 at 17:56
  • @Slaw yes, you are right! I tried to catch the exception and got: "java.lang.IllegalStateException: Not on FX application thread; currentThread = pool-2-thread-1". – P. Daimaou Aug 22 '18 at 17:58
  • 1
    Possible duplicate of [How to use PauseTransition method in JavaFX?](https://stackoverflow.com/questions/30543619/how-to-use-pausetransition-method-in-javafx) – user1803551 Aug 22 '18 at 19:39

1 Answers1

0

Give this a shot I added the Platform.runlater(()->...

public class Main extends Application {

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

    @Override
    public void start(Stage primaryStage) {
        BorderPane root = new BorderPane();
        GridPane block = new GridPane();
        block.addRow(0, new Text("HELLO"));

        new Timer().schedule(
                new TimerTask() {
                    @Override
                    public void run() {
                        System.out.println("IN");
                        Platform.runLater(()->block.addRow(1, new Text("WORLD")));
                        System.out.println("OUT");
                    }
                },
                0,
                2*1000);//2 seconds

        root.setCenter(block);

        Scene scene = new Scene(root, 1280, 720);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

}
Matt
  • 3,052
  • 1
  • 17
  • 30