java - 康威生命游戏持续更新

标签 java swing animation graphics

我在尝试单击 JButton 并不断更新康威的生命游戏时遇到了麻烦。所以我首先要给出生命游戏的规则并模拟和计算计数器的位置。然后通过设置 JButton 的背景颜色来更新框架,然后延迟并重复。但问题是,当我按下开始按钮时,由于我尝试使用 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();
  }
}

最佳答案

您声明:

But the problem is when I press the start button, it got stucked due to the fact i was trying to use while loop.

然后摆脱 while (true) 循环,因为这一切都会占用 Swing 事件线程,导致 GUI 无用。您有一个 Swing 计时器,您可以在计时器的 ActionListener 中调用模型的 update 方法,以便在计时器的每次滴答时调用它,然后您就不需要 while 循环。其他选项包括保留 while (true) 循环,但在后台线程中调用它,但如果这样做,请注意仅在 Swing 事件线程上更新 GUI。

...Sorry for the formatting though...

我已经为您格式化了您的代码,但为了将来的引用,您需要阅读本网站有关如何格式化问题和包含代码的帮助部分。也看看here .

<小时/>

其他随意的想法:

  • 关于Timer tm = new Timer(1000,this);,我尝试避免让我的 GUI 类实现监听器接口(interface),因为它会强制类执行过多操作,从而违反单一职责原则。最好使用单独的监听器类、分配监听器的 Control 类或匿名内部类。
  • 有关 Swing 线程问题的更多信息,请参阅 Lesson: Concurrency in Swing
<小时/>

有关匿名内部类的更多信息,请再次摆脱 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();

关于java - 康威生命游戏持续更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25837024/

相关文章:

java - Netbeans 项目的主类已被删除

java - android studio json数据解析错误

java - JPanel 和 BufferedImage

angularjs - Angular 动画滑动面板-加载 View 时显示第二个

java - 用于分隔每行的 String.format() 语句仅空格大括号

java - 从表单中获取信息并将其粘贴到jsp

java - MigLayout,禁用 JButton 宽度调整大小

java - 是否应该在 EDT 上更新 JUNG 图?

javascript - 绘制SVG路径的最简单方法

c++ - 在动画 Opengl c/c++ 方面需要帮助