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/