有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JavaFX延迟for循环中的颜色更改

我有一个网格窗格,其中填充了矩形(4x4),每个矩形都需要更改颜色,并且需要按照特定的顺序进行操作,其间有一个延迟。顺序由数组中的模型给出

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

我尝试了很多方法来增加延迟,这样它们就不会一下子激活,但我似乎无法解决这个问题

我的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);
     }

 }

我尝试过的事情:时间线:

 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中也可见?类似这样的东西:视图。enableRegularBlock(0,0)->;延迟500毫秒->;看法enableRegularBlock(0,1)->;延迟500毫秒

谢谢


共 (1) 个答案

  1. # 1 楼答案

    不能在线程/事件处理程序等外部添加循环

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

    激活运行多个循环的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();