如何在每次迭代之间使这个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 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() { @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(); 

btw只显示最后一次迭代的原因是gui更新(重绘)是在一个单独的事件中完成的,但是为了让另一个事件触发你需要从你没有的监听器方法返回

我展示的计时器是一个更复杂的迭代,它允许其他事件在迭代之间运行,允许gui显示更改

检查我的post,显示两个方法java.swing.Timer #setDelay(int)

正确使用Thread.sleep(int)

java等待光标显示问题