Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 959
i . Avatar asked May 26 '13 23:05

i .


2 Answers

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(
        Duration.millis(2500),
        ae -> doSomething()))
    .play();

Alternatively, you can use a convenience method from ReactFX:

FxTimer.runLater(
        Duration.ofMillis(2500),
        () -> doSomething());

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

like image 127
Tomas Mikula Avatar answered Sep 24 '22 20:09

Tomas Mikula


berry120 answer works with java.util.Timer too so you can do

Timer timer = new java.util.Timer();

timer.schedule(new TimerTask() {
    public void run() {
         Platform.runLater(new Runnable() {
            public void run() {
                label.update();
                javafxcomponent.doSomething();
            }
        });
    }
}, delay, period);

I used this and it works perfectly

like image 28
Flo C Avatar answered Sep 24 '22 20:09

Flo C