如何在每次迭代之间使此Java for循环暂停1/2秒?

问题描述

|
private class MultipleGensListener implements ActionListener
   {
    public void actionPerformed(ActionEvent e)
        {
            for(int i = 0; i < 25; i++)
            {
                game.runSimulationOneGen();
                changeGrid();
            }
        }
   }
//这是循环。 changeGrid方法在GUI上显示游戏网格,但是 //只有第25次迭代在屏幕上可见。我希望每个人都是 //在循环继续之前,可以看到约半秒钟。 //我在这里看到了一些非常接近我所问问题的问题, //但我只是不太了解如何将其应用到我的程序中。 // 谢谢你的帮助。     

解决方法

        如果仿真执行的代码很快,并且不占用过多的CPU和时间,则可以考虑使用Swing计时器进行循环和延迟。否则,您将需要使用后台线程,例如可以使用SwingWorker对象。 例如如果同时使用Swing Timer和SwingWorker:
   private class MultipleGensListener implements ActionListener {
      protected static final int MAX_INDEX = 25;

      public void actionPerformed(ActionEvent e) {
         int timerDelay = 500; // ms delay
         new Timer(timerDelay,new ActionListener() {
            int index = 0;

            public void actionPerformed(ActionEvent e) {
               if (index < MAX_INDEX) { // loop only MAX_INDEX times
                  index++;

                  // create the SwingWorker and execute it
                  new SwingWorker<Void,Void>() {
                     @Override
                     protected Void doInBackground() throws Exception {
                        game.runSimulationOneGen(); // this is done in background thread.
                        return null;
                     }

                     @Override
                     protected void done() {
                        changeGrid(); // this is called on EDT after background thread done.
                     }
                  }.execute(); // execute the SwingWorker
               } else {
                  ((Timer) e.getSource()).stop(); // stop the timer
               }
            }
         }).start(); // start the Swing timer
      }
   }
    ,        绝不阻止GUI事件线程 您可以为此使用计时器,并且仅触发25次
final Timer t = new Timer(500,null);
t.addActionListener(new ActionListener(){
     int i=0;
     public void actionPerformed(ActionEvent e){
         game.runSimulationOneGen();//run 1 iteration per tick
         changeGrid();
         if(i>25){t.stop();}
         i++;
     }
});
t.setRepeats(true);
t.start();
顺便说一下,仅显示最后一次迭代的原因是,gui更新(重绘)是在单独的事件中完成的,但是要让另一个事件触发,您需要从未使用的监听器方法中返回 我展示的Timer是一个更复杂的迭代,它允许其他事件在迭代之间运行,从而使gui显示更改     ,        检查我的帖子,其中显示了两种方法java.swing.Timer#setDelay(int) 和 正确使用Thread.sleep(int) java等待光标显示问题     

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...