Timers and javafx


I am trying to write a code that will make things appear on the screen at predetermined but irregular intervals using javafx. I tried to use a timer (java.util, not javax.swing) but it turns out you can't change anything in the application if you are working from a separate thread.(Like a Timer) Can anyone tell me how I could get a Timer to interact with the application if they are both separate threads?

5/27/2013 10:39:42 AM

Accepted Answer

If you touch any JavaFX component you must do so from the Platform thread (which is essentially the event dispatch thread for JavaFX.) You do this easily by calling Platform.runLater(). So, for instance, it's perfectly safe to do this:

new Thread() {
    public void run() {
        //Do some stuff in another thread
        Platform.runLater(new Runnable() {
            public void run() {
5/27/2013 11:03:36 AM

You don't need java.util.Timer or java.util.concurrent.ScheduledExecutorService to schedule future actions on the JavaFX application thread. You can use JavaFX Timeline as a timer:

new Timeline(new KeyFrame(
        ae -> doSomething()))

Alternatively, you can use a convenience method from ReactFX:

        () -> doSomething());

Note that you don't need to wrap the action in Platform.runLater, because it is already executed on the JavaFX application thread.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow