Javafx Not on fx application thread when using timer

前端 未结 1 1805
臣服心动
臣服心动 2020-12-05 15:50

I\'m using this

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import javafx.application.Application;
import javafx.applicatio         


        
相关标签:
1条回答
  • 2020-12-05 16:31

    It may be because you misunderstood how Platform.runLater() works..

    The correct code snippet would be:

    public void moveCircle(Circle circle, Scene scene) {
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                Platform.runLater(() -> {
                    circle.setCenterX(random((int) scene.getX()));
                    circle.setCenterY(random((int) scene.getY()));
                });
            }
        }, 1000, 1000);
    }
    

    But:

    I would strongly recommend you to not use Timer but TimeLine instead! It is part of the JavaFX API and you do not have to do these Platform.runLater() calls. This is just quickly hacked together, but you get the idea:

    public void moveCircle(Circle circle, Scene scene) {
        Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1), ev -> {
            circle.setCenterX(random((int) scene.getX()));
            circle.setCenterY(random((int) scene.getY()));
        }));
        timeline.setCycleCount(Animation.INDEFINITE);
        timeline.play();
    }
    
    0 讨论(0)
提交回复
热议问题