我在点击JButton并不断更新Conway的“生活的游戏”时遇到了麻烦。所以我要做的就是首先给出游戏规则,然后模拟和计算计数器的位置。然后通过将背景颜色设置为JButton来更新帧,然后延迟并重复。但问题是,当我按下start按钮时,由于我试图使用while
循环,它被卡住了。
有一个单独的软件包,叫做AI_Processor,它只是模拟和计算都是正确的,只是更新有一些问题。
代码部分:
public void updateFrame() {
AI.AI_Movement_Update();
addColour();
}
public void addColour() {
for (int i = 0; i < fieldHeight; i++) {
for (int j = 0; j < fieldWidth; j++) {
if (AI.getPosB(j, i) == true) {
testMolecules[i][j].setBackground(Color.green);
} else {
testMolecules[i][j].setBackground(Color.black);
}
}
}
}
Timer tm = new Timer(1000,this);
if (ae.getSource() == start) {
while(true) {
updateFrame();
tm.start();
}
}
发布于 2014-09-15 03:18:33
你声明:
但问题是当我按下start按钮时,由于我试图使用
循环的事实,它被阻塞了。
然后去掉while (true)
循环,因为这样做只会占用Swing事件线程,使您的图形用户界面变得无用。您有一个Swing计时器,并且可以在计时器的ActionListener中调用模型的更新方法,这样计时器的每次滴答都会调用它,这样就不需要while循环了。其他选项包括保留while (true)
循环,但在后台线程中调用它,但如果这样做,请注意仅在Swing事件线程上更新您的图形用户界面。
格式设置的
...Sorry ...
我已经为你格式化了你的代码,但为了将来的参考,你需要阅读这个网站的帮助部分,关于如何格式化问题和包含代码。也可以看看here。
其他随机想法:
Timer tm = new Timer(1000,this);
,我尽量避免让我的图形用户界面类实现侦听器接口,因为它迫使类做太多的事情,打破了单一责任原则。最好使用单独的侦听器类、分配侦听器的控件类或匿名内部类。要获得更多关于匿名内部类的信息,同样,去掉while (true)
,改为尝试如下所示:
// note that TIMER_DELAY is a constant, and needs to be smaller than 1000, perhaps 20?
Timer tm = new Timer(TIMER_DELAY, new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
updateFrame();
}
});
// the start call below can only be called inside of a method or a constructor
tm.start();
发布于 2014-09-15 03:18:28
编辑:
抱歉,以前的解决方案不好:-(
编辑:
为此,您可以使用匿名内部类
请参阅http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
请参阅http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html
如果你使用定时器,那么你应该通过一个实例的ActionListener定时器创建一个新的线程,所以虽然不是必须的…
未测试:
public void updateFrame(){
AI.AI_Movement_Update();
addColour();
}
public void addColour() {
for (int i = 0; i < fieldHeight; i++) {
for (int j = 0; j < fieldWidth; j++) {
if (AI.getPosB(j, i) == true) {
testMolecules[i][j].setBackground(Color.green);
} else {
testMolecules[i][j].setBackground(Color.black);
}
}
}
}
if(ae.getSource() == start)
new Timer(1000,new ActionListener(){
updateFrame();
}).start();
https://stackoverflow.com/questions/25837024
复制相似问题