JavaFX延迟for循环中的颜色变化

问题描述 投票:0回答:1

我有一个填充矩形(4x4)的网格窗格,每个矩形需要更改颜色,需要按特定顺序完成,并且它们之间有延迟。顺序由数组中的模型给出。

演示者在for循环中使用数组,然后告诉视图按索引更改块的颜色。

我已经尝试了很多东西来增加延迟,这样他们就不会立刻激活所有东西,但我似乎无法弄明白。

我的循环:

 int[][] grid = model.getGrid();

 for (int i = 0; i < grid.length; i++) {
     for (int j = 0; j < grid[i].length; j++) {
            view.enableRegularBlock(i, j);
     }

 }

我尝试过的事情:TimeLine:

 public void enableRegularBlock(int i, int j) {
    Timeline timeline = new Timeline(new KeyFrame(
            Duration.millis(500),
            ae -> {
                Rectangle r = blockArray[i][j];
                r.setFill(activeColor);
                startTimer += 500;
            }));
    timeline.play();
 }

这是在for循环内运行,不能同时激活所有矩形。

线:

 int[][] grid = model.getGrid();

    for (int i = 0; i < grid.length; i++) {
        for (int j = 0; j < grid[i].length; j++) {
            final int row = i;
            final int col = j;
            Thread t = new Thread(){
               public void run() {
                   try{

                        Platform.runLater(new Runnable() {
                           @Override
                           public void run() {
                               view.enableRegularBlock(row, col);
                           }
                       });
                       Thread.sleep(500);
                   } catch(InterruptedException v){System.out.println(v);}
               }
           };

           t.start();

        }

    }

这也会立即激活所有矩形。

有没有办法在ui中可见的矩形激活之间添加延迟?所以像这样:view.enableRegularBlock(0,0) - >延迟500ms - > view.enableRegularBlock(0,1) - >延迟500ms ......

谢谢!

java javafx
1个回答
0
投票

您不能在线程/事件处理程序之外添加循环,例如。

从循环开始的多个时间轴与多个线程并行运行。

激活运行多个周期的Timeline中的所有元素:

Timeline timeline = new Timeline(new KeyFrame(Duration.millis(500), new EventHandler<ActionEvent>() {

    private int i = 0;
    private int j = 0;

    @Override
    public void handle(ActionEvent event) {
        Rectangle r = blockArray[i][j];
        r.setFill(activeColor);
        j++;
        if (j >= blockArray[i].length) {
            // "reset" inner loop, next step in outer loop
            j = 0;
            i++;
        }
    }
}));

// assuming same size of inner arrays here
timeline.setCycleCount(blockArray.length * blockArray[0].length);

timeline.play();

或使用Thread

new Thread(() -> {
    for (int i = 0; i < grid.length; i++) {
        for (int j = 0; j < grid[i].length; j++) {
            final Rectangle r = blockArray[i][j];

            Platform.runLater(() -> r.setFill(activeColor));
            try {
                Thread.sleep(500);
            } catch(InterruptedException v){System.out.println(v);}
        }
    }
}).start();
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.