How to refresh javaFX group after each shape drawn in cycle?

Tookuk :

Let's say that I need to draw several points on the screen. One after another, with a small pause after each point. How to do this in JavaFX?

My sample program just waits till the end of a cycle, then all the points appear simultaneously.

public class PointByPoint extends Application {

public static void main(String[] args) {
    launch(args);
}

@Override
public void start(Stage stage) throws Exception {
    GridPane root = new GridPane();
    Button startButton = new Button("start");
    Group group = new Group();
    root.add(startButton, 0, 0);
    root.add(group, 0, 1);
    Scene scene = new Scene(root, 1000, 1000);
    stage.setScene(scene);
    stage.show();

    startButton.setOnAction(actionEvent -> draw100points(group));
}

private void draw100points(Group group) {
    for (int i = 0; i < 100; i++){
        Circle circle = new Circle();
        circle.setRadius(1);
        circle.setCenterY(ThreadLocalRandom.current().nextInt(1, 1000 + 1));
        circle.setCenterX(ThreadLocalRandom.current().nextInt(1, 1000 + 1));
        circle.setFill(Color.BLACK);
        group.getChildren().add(circle);
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}}
James_D :

You're blocking the FX Application Thread with sleep(...), so it can't redraw the scene each time. Use a Timeline instead:

private void draw100points(Group group) {
    Timeline timeline = new Timeline();
    int interval = 10 ; // milliseconds
    for (int i = 0; i < 100; i++){
        Circle circle = new Circle();
        circle.setRadius(1);
        circle.setCenterY(ThreadLocalRandom.current().nextInt(1, 1000 + 1));
        circle.setCenterX(ThreadLocalRandom.current().nextInt(1, 1000 + 1));
        circle.setFill(Color.BLACK);
        KeyFrame keyFrame = new KeyFrame(Duration.millis(interval * i),
            e -> group.getChildren().add(circle));
        timeline.getKeyFrames().add(keyFrame);
    }
    timeline.play();
}

A 10 millisecond gap may be too little to properly see that; you might want to slow the animation down a little by increasing the interval.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=317823&siteId=1