JavaFX 2 时间线 setcyclecount()

JavaFX 2 Timeline setcyclecount()

我在 javase8 和 netbeans 8.0.2 中使用 javafx,我制作了随机生成的形状图像并使用时间轴顺序显示它们。但最后一张图片没有显示。 timeline.setcyclecount(12) 我使用 java 生成 12 张图像,但未在时间轴中显示 12. 图像。

public class JavaFXApplication3 extends Application {
        int k;
        Timeline timeline;

        class ResizableCanvas extends Canvas {
            private void draw() {
                int[] uyaran = {3, 7, 12};
                boolean[] type = new boolean[12];
                for (int i = 0; i < 12; i++) {
                    type[i] = false;
                }
                for (int v : uyaran) {
                    type[v - 1] = true;
                }
                double w = getWidth();
                double h = getHeight();
                GraphicsContext gc = getGraphicsContext2D();
                gc.clearRect(0, 0, w, h);
                gc.setFill(Color.RED);
                System.out.println(k);
                if (type[k]) {
                    gc.fillOval(0, 0, w, h);
                }
                k++;
            }
        }

        @Override
        public void start(Stage stage) throws Exception {
            k = 0;
            ResizableCanvas canvas = new ResizableCanvas();
            timeline = new Timeline(new KeyFrame(Duration.millis(1000), ae -> canvas.draw()));
            timeline.setCycleCount(12);
            timeline.setOnFinished(ActionEvent -> {
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException ex) {}
                stage.close();
            });
            timeline.play();
            Pane pane = new Pane();
            pane.getChildren().add(canvas);
            canvas.widthProperty().bind(pane.widthProperty());
            canvas.heightProperty().bind(pane.heightProperty());
            stage.setScene(new Scene(pane));
            stage.show();
        }

}

您正在 FX 应用程序线程上调用 Thread.sleep(...),这会阻塞线程并阻止其更新。最后的椭圆只有在暂停结束时才真正呈现,但当然你随后关闭 window 所以你永远看不到它。

使用 PauseTransition 暂停,并在暂停结束后使用其 onFinished 处理程序执行某些操作:

        timeline.setOnFinished(ae -> {
            PauseTransition pause = new PauseTransition(Duration.seconds(10));
            pause.setOnFinished(event -> stage.close());
            pause.play();
        });