Home java Multithreading in JavaFX. Not on FX application thread

Multithreading in JavaFX. Not on FX application thread

Author

Date

Category

I have a stream

Thread skillshowin = new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            newskill.setStyle("visibility: true");
            Thread.sleep(10000);
            Thread.interrupted();
        } catch (Exception e) {
            skill.setText("" + Integer.valueOf(skill.getText()) + 5);
            newskill.setStyle("visibility: false");
        }
    }
});
skillshowin.start();

But I get the error Exception in thread "Thread-5" java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-5when executing skill.setText


Answer 1, authority 100%

To modify UIin other threads in JavaFX, you must use other means:

Platform.runLater():

Option with lambda:

Platform.runLater(() -> {
    //your code
});

Alternatively with Runnable:

Platform.runLater(new Runnable() {
    @Override
    public void run() {
        //your code
    }
});

As well as Serviceand Task. The Serviceis more powerful than the normal Thread. Changing UIinside Taskwill not throw out Not on FX application thread, but inside Taskyou also need to write Platform.runLater(), otherwise all sorts of errors may occur.

Service service = new Service() {
    @Override
    protected Task createTask() {
        return new Task() {
            @Override
            protected Object call() throws Exception {
                Platform.runLater(() -> {
                    //your code
                });
                return null;
            }
        };
    }
};
service.start();

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions