Timers and javafx

2020-01-29 07:22发布

问题:

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?

回答1:

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() {
                label.update();
                javafxcomponent.doSomething();
            }
        });
    }
}.start();


回答2:

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.



回答3:

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