Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How JavaFX application thread works?

I have a problem with Java FX application thread. Here is a pseudo-code:

showMenu();
//Contoller which waits for action(pressing button)...
showLoadingPic();
Thread.sleep(2000);
showMap();

The problem is that the sleep occurs in window which is displayed in showMenu(), showLoadingPic() is not shown at all, and at the end window in showMap() is shown.

The scene in showLoadingPic has a progress bar which runs 2 secs which is the same time as Thread.sleep(2000).

So it seems like javafx application thread blocks showLoadingPic() and showLoadingPic() runs at background.

Can somebody help me to fix this??

Thank you in advance!

like image 460
ulzhan Avatar asked Nov 03 '13 16:11

ulzhan


People also ask

Can a JavaFX application run in a separate thread?

However, if the task is lengthy, and in response to a user interaction, it must be dealt in a separate thread because a JavaFX application thread cannot render controls or respond to events while the thread is bound to that task. This certainly causes the GUI to freeze and become unresponsive.

Is the JavaFX scene graph thread-safe?

The JavaFX scene graph, which represents the graphical user interface of a JavaFX application, is not thread-safe and can only be accessed and modified from the UI thread also known as the JavaFX Application thread. Implementing long-running tasks on the JavaFX Application thread inevitably makes an application UI unresponsive.

What is the use of serviceclass in JavaFX?

The Serviceclass methods and states must only be accessed on the JavaFX Application thread. The purpose of this class is to help the developer to implement the correct interaction between the background threads and the JavaFX Application thread.

How do I run a JavaFX application in the background?

Use a Worker (Task, Service) from the JavaFX Application thread if you want to do something in the background. Use Platform.runLater from a background thread if you want to do something on the JavaFX Application thread.


1 Answers

There is a Java FX event dispatch thread, which handle all GUI-related tasks. You must update all UI components in this thread. Long-running tasks, like Thread.sleep should never be executed in this thread, since windows will hang, and the GUI will be frozen.

Execute all your code in the application main thread, and perform only GUI tasks in JavaFX thread, by calling Platform.runLater.

References on this topic:

  • Concurrency in JavaFX, from Oracle
  • Related SO question
like image 58
Guillaume Poussel Avatar answered Sep 22 '22 23:09

Guillaume Poussel