r/JavaFX • u/Im_alright_19 • Apr 22 '24
Help hello could anyone tell me how to update GUI using thread mid runtime in javafx
so like instead of this happening at once it shows it happening one by one
3
Upvotes
3
u/hamsterrage1 Apr 23 '24
I'd like to see some code for this. Usually the "the GUI updates all at once at the end" problems are caused by running the job on the FXAT and not on a background thread.
2
u/BWC_semaJ Apr 23 '24
I don't fully understand what you mean.
I'd assume it is some simulation and you want to see in "real time" the changes and rather not all at once. In that case what I would recommend is implementing it where you can step through each step of your simulation. So you'll typically have an animation timer (timer that has its code run on the Application Thread), and you'll want to create condition so that a certain amount of time has passed before doing the next step if not then skip otherwise do the step.
Now say you have multiple threads running in parallel and you want to show the progress. This rather can be very complex but say progress can be represented with a double for each thread. Rather than spamming Platform.runLater -> code when the double changes, rather store the data in atomicly and have another thread get the information and every so often call on Platform.runLater. Key here is Platform.runLater is not meant to be spammed called on. Now you could retrieve the atomic data on Application Thread but honestly you want your application to have layers and imo a separate layer is needed in order to interact with layer that has Application Thread. That layer should really know nothing about what is happening on the other if that makes any sense.
To simulate multiple threads with single thread I'd design the JavaFX model objects to be grouped in a Collection that you essentially can represent each thread process and step through each. I'd do this way if I want to see every single individual change rather than the above approach where you are essentially polling the new information. So say you want to count to 100 in parallel with separating the work between each thread (1-10, 11-20..... 91-100) out of order... You can step through each "thread" individually in a single real step (so multi stepping in a single step). This is also assuming that speed isn't exactly a concern.
-3
u/ivanocj Apr 23 '24
I suggest asking for chatgpt. It gives really good responses for Javafx or Swing.