我在Java中实现我的生活游戏时遇到了问题。
在GUI中,我有按钮来决定游戏的初始状态(振荡器,滑翔机等),然后使用Action Listener设置第一个棋盘并显示它。
然后我有一个函数,可以计算我的细胞的邻居,并设置我的细胞的颜色。但是当我想重复游戏n次时,我有一个问题,因为我不知道如何设置时间间隔。
此时此刻,我看不到游戏的每一步,但只看到了最后一步。
下面是我的ActionListener:
private ActionListener buttonsListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == button1)area = setButton1(getBoardWidth(), getBoardHeight());
if (source == glider) area = setGlider(getBoardWidth(), getBoardHeight());
if (source == oscilator) area = setOscilator(getBoardWidth(), getBoardHeight());
setBoard(area, board);
}
};函数setBoard()接受带0和1的it数组,并将其转换为带颜色的JButton[][]数组。
我尝试使用包含startTheGame()函数的重写方法run(),该函数检查邻域并设置整数数组。我需要多次这样做,但我不能设置时间间隔。
@Override
public void run() {
startTheGame(area);
setBoard(area, board);
}发布于 2020-04-06 02:21:58
您应该使用此计时器schedule。
因此,您必须像这样定义一个自定义TimerTask:
import java.util.TimerTask;
public class UserTimerTask extends TimerTask{
@Override
public void run() {
startTheGame(area);
setBoard(area, board);
}
}然后像这样包装你的代码:
// daemon means, background. If every task is a demon task, the VM will exit
Bolean isDaemon = false;
Timer timer = new Timer("nameOfThread",isDaemon);
TimerTask task = new UserTimerTask();
// Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay
// both parameters are in milliseconds
timer.schedule(task,0,1000);https://stackoverflow.com/questions/61045384
复制相似问题