java - 如何让这个 java for 循环在每次迭代之间暂停 1/2 秒?

标签 java swing loops timer delay

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 Timer 来执行循环和延迟。否则,您需要使用后台线程,例如可以使用 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
      }
   }

关于java - 如何让这个 java for 循环在每次迭代之间暂停 1/2 秒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6168179/

相关文章:

java - 更改 JTabbedPane 边框的颜色

java - 按两个条件对 hashSet 进行排序

java - 未检测到 JMenuItem Actionlistener

mysql - Node.js 在循环中与 MySQL 链接 promise

java - 循环是否每次都需要更长的时间来执行?

java - Android Java 日历替代品,具有以下功能

java - 在父类和子类的构造函数中调用重写方法

java - java中HttpURLConnection意外断开

java - 创建前端并用 Java 连接它们

php - 从 foreach 循环中删除最后一个逗号