简体   繁体   English

JavaFX延迟绘制形状

[英]JavaFX draw shapes with delay

How can I draw shapes with delay? 如何延迟绘制形状? For example at the beginning, draw few rectangles, after 1 second draw fillOval, after 3 seconds draw another oval and so on. 例如,在开始处绘制几个矩形,在1秒后绘制fillOval,在3秒后绘制另一个椭圆,依此类推。

You are describing an animation. 您正在描述动画。 For that, you should use the Animation API . 为此,您应该使用Animation API

Eg, using a Timeline : 例如,使用Timeline

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Ellipse;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;

public class ShapeAnimationExample extends Application {

    private final Random rng = new Random();


    @Override
    public void start(Stage primaryStage) {


        List<Rectangle> fewRectangles = new ArrayList<>();
        for (int i = 0 ; i < 5 ; i++) {
            Rectangle r = new Rectangle(rng.nextInt(300)+50, rng.nextInt(300)+50, rng.nextInt(100)+50, rng.nextInt(100)+50);
            r.setFill(randomColor());
            fewRectangles.add(r);
        }

        List<Ellipse> ovals = new ArrayList<>();
        for (int i = 0 ; i < 5 ; i++) {
            Ellipse e = new Ellipse(rng.nextInt(400)+50, rng.nextInt(400)+50, rng.nextInt(50)+50, rng.nextInt(50)+50);
            e.setFill(randomColor());
            ovals.add(e);
        }

        Pane pane = new Pane();
        pane.setMinSize(600, 600);

        Timeline timeline = new Timeline();
        Duration timepoint = Duration.ZERO ;
        Duration pause = Duration.seconds(1);

        KeyFrame initial = new KeyFrame(timepoint, e -> pane.getChildren().addAll(fewRectangles));
        timeline.getKeyFrames().add(initial);

        for (Ellipse oval : ovals) {
            timepoint = timepoint.add(pause);
            KeyFrame keyFrame = new KeyFrame(timepoint, e -> pane.getChildren().add(oval));
            timeline.getKeyFrames().add(keyFrame);
        }

        Scene scene = new Scene(pane);
        primaryStage.setScene(scene);
        primaryStage.show();

        timeline.play();
    }

    private Color randomColor() {
        return new Color(rng.nextDouble(), rng.nextDouble(), rng.nextDouble(), 1.0);
    }

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

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

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