1

Im trying to update the primaryStage after a set amount of time. This gives me: java.lang.IllegalStateException: Not on FX application thread; I've been searching for a solution on StackOverflow and I found some people suggest using

Platform.runLater(new Runnable ...)

Source: https://stackoverflow.com/a/17851019/5314214

But still I can't figure out how to make it work after a set amount of time.

My code:

Timer timer = new Timer();
timer.schedule(new TimerTask() {
    @Override
    public void run() {
        update(primaryStage);
        timer.cancel();
    }
}, 400);
Community
  • 1
  • 1
Alex
  • 839
  • 1
  • 12
  • 24

2 Answers2

3

This is the way to do it:

Timer timer = new Timer();
timer.schedule(
    new TimerTask() {
        @Override
        public void run() {
            Platform.runLater(() -> update(primaryStage));
            timer.cancel();
        }
    }, 400
);

Anytime you want to modify your stage from another thread you need to do it through Platform.runLater as only the FX application thread is allowed to do it, indeed JavaFX has not been designed to be used by concurrent threads to prevent bugs hard to fix.

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
2

Another solution is to use a PauseTransition. The benefit is that it you don't have to use Platform.runLater()

  PauseTransition pauseTransition = new PauseTransition(Duration.millis(400));
  pauseTransition.setOnFinished(e -> updateStage());
  pauseTransition.playFromStart();
jns
  • 6,017
  • 2
  • 23
  • 28