I have a JavaFX application in which I want to be a Label that updates frequently and displays the current date and time.
Problem is, that I can’t call JavaFX methods from a second thread and using the main thread makes the UI unresponsive.
So how do I manipulate this Label?
That still makes the main thread unresponsive, because I have to run an endless loop. Or is there an other way to frequently (1-2 times a second) update a Component?
Create a new Thread with a Runnable that contains your infinite loop, and in the loop put a Thread.sleep(500) to sleep 500 milliseconds between each execution.
You can not call JavaFX functions from a second thread! That’s the problem.
I feel like you’re not understanding the advice you’re being given. Have you tried googling “javafx threading”? There are a ton of results, including:
- http://docs.oracle.com/javafx/2/threads/jfxpub-threads.htm
- https://docs.oracle.com/javase/8/javafx/interoperability-tutorial/concurrency.htm
- https://stackoverflow.com/questions/16708931/javafx-working-with-threads-and-gui
- https://stackoverflow.com/questions/22772379/updating-ui-from-different-threads-in-javafx
Please make sure you understand what people are telling you to do before you tell them it won’t work.
Basically, you need to do the “work” on another thread, and then use Platform.runLater() to update your label. Presumably the Platform.runLater() call would be inside the loop. The loop would not be on the UI thread.
Alright, got it working now. I only got the advice the third time I read the post.
My fault :persecutioncomplex: