Chetna rustagi
Chetna rustagi

Reputation: 481

javafx thread exception on javafx scene

Related to my question : Bind label with two different values-javafx , now I am able to bind two values to a label and update on my UI in my eclipse. Since my application is updating the value very frequently I have done the bind work in a timer as shown :

Timeline timer = new Timeline(new KeyFrame(Duration.seconds(1), new 
EventHandler<ActionEvent>() {

    @Override
    public void handle(ActionEvent event) {
            answerQuesLbl.textProperty().bind(answerConnector.getNoOfAnswers().asString().concat("/").concat(answerConnector.getNoOfQuestions().asString()));
    }
}));

timer.setCycleCount(Timeline.INDEFINITE);
timer.play();

This is working fine within my eclise, but when I create a build of my project using
mvn assembly:assembly -Dmaven.test.skip=true

and running the project using bat file, everything works fine , even the values are getting updated but not on UI ,it is giving an exception like :

Exception in thread "Thread-7" java.lang.IllegalStateException: 
    Not on FX application thread; currentThread = Thread-7
    at com.sun.javafx.tk.Toolkit.checkFxUserThread(Toolkit.java:229)
    at com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(QuantumToolkit.java:423)

My build is good, do i need to create different kind of thread for this?

Upvotes: 0

Views: 400

Answers (1)

Itai
Itai

Reputation: 6911

There are two issues with your code:
1. There is no need to re-bind every second.
2. Bound properties receive change notifications on the thread that performed the change, so if answerConnector.getNoOfAnswers is changed on another thread, you will get a not-on-FX-thread exception.

You can either change the event handler so that you set the text every second (the Timeline ensures it will be called on the FX thread), or else make sure the original changed is performed on the FX thread.

Upvotes: 2

Related Questions