简体   繁体   English

循环绘制每个形状后如何刷新javaFX组?

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

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?如何在 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();
        }
    }
}}

You're blocking the FX Application Thread with sleep(...) , so it can't redraw the scene each time.您使用sleep(...)阻塞了 FX 应用程序线程,因此它无法每次都重绘场景。 Use a Timeline instead:改用Timeline

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; 10 毫秒的间隔可能太小而无法正确看到; you might want to slow the animation down a little by increasing the interval.您可能希望通过增加间隔来稍微减慢动画速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM