JavaFX working with threads and GUI
As puce says, you have to use Task
or Service
for the things that you need to do in background. And Platform.runLater
to do things in the JavaFX Application thread from the background thread.
You have to synchronize them, and one of the ways to do that is using the class CountDownLatch
.
Here is an example:
Service<Void> service = new Service<Void>() { @Override protected Task<Void> createTask() { return new Task<Void>() { @Override protected Void call() throws Exception { //Background work final CountDownLatch latch = new CountDownLatch(1); Platform.runLater(new Runnable() { @Override public void run() { try{ //FX Stuff done here }finally{ latch.countDown(); } } }); latch.await(); //Keep with the background work return null; } }; } }; service.start();
Use a Worker
(Task
, Service
) from the JavaFX Application thread if you want to do something in the background.
http://docs.oracle.com/javafx/2/api/javafx/concurrent/package-summary.html
Use Platform.runLater
from a background thread if you want to do something on the JavaFX Application thread.
It's too late to answer but for those who have the error, here is the solution XD
You can use one Thread.
Use the lambda expression for the runnable
in the thread and the runlater
.
Thread t = new Thread(() -> { //Here write all actions that you want execute on background Platform.runLater(() -> { //Here the action where is finished the actions on background }); });t.start();