'How to solve (java.lang.IllegalStateException: Not on FX application thread)?

I am working on simple Brick Breaker game on JavaFX. Until now everything was working fine but when I tried to add Label which was updating time it showed up this error. I think problem is in Timer class because it executes on different thread so JavaFX main thread yields this exception. But why this happens? In Java Swing it is not illegal to use different threads? Can anyone help me?

This is Main Class which creates new task which on each second adds new time to label and sends it to Controller which adds this label to fxml.

Time should be shown here

protected static Label get Time Label() {
    timeShowLabel.setLayoutX(507.0);
    timeShowLabel.setLayoutY(-2.0);
    Platform.runLater(() -> {
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
                timeShowLabel.setText(formatter.format(new Date()));
            }
        }, 1000, 1000);
    });
    return timeShowLabel;

}

Exception Image

Controller class

public void initialize(URL arg0, ResourceBundle arg1) {
        // TODO Auto-generated method stub
        setRandomColor();
        mainLayout.getChildren().add(Main.getTimeLabel());
    }


Solution 1:[1]

You code is conceptually wrong. Platform.runLater executes the given code on the FX application thread but you do not want to put the timer scheduling on that thread. Instead the code that is run by the timer must be wrapped in Plaform.runLater because it sets the label which has to happen on the FX application thread.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mipa