java - 为什么我的 run() 方法没有从我的 Actionlistener 中正确调用

标签 java eclipse multithreading

我正在致力于 Snake 的实现,并且已经基本完成。我唯一的问题是,当我单击用于开始新游戏的 JMenuItem 时,游戏会卡住。相关代码如下:

             this.newGame.addActionListener(new ActionListener()
                 {
             @Override
             public void actionPerformed(ActionEvent e){
                 neuesSpiel();
             }

                 });





             public void neuesSpiel()
             {     //The old snake game is finished and the playing field is reseted
                  if(snake!=null)
                  {
                      snake.beendeSpiel();

                      for(int i=0; i<20;i++)
                      {
                           for(int j=0;j<10;j++)
                           {    
                            spielfeld[i][j] = false;
                            }
                      }

                  }//the new snake game is created below
                  snake = new Snake(null,null, 10,5, this);     
                  Snake snake2 = new Snake(snake,null,11,5,this);
                  snake.hintermann = snake2;
                  snake2.hintermann = new Snake(snake2,null,12,5,this);

                  snake.run();
               }

在 Snake 类中:

public void run()
{
Game.zf.requestFocus();

while(spiellauf){
try
{
    Thread.sleep( 120 );
} 
catch ( InterruptedException e ) { }
if(spiellauf)
bewege(); //the Snake Block is moved
}

我很确定 run() 方法是问题所在,因为如果我不调用该方法,游戏就不会卡住。此外,neuesSpiel() 方法也应该没问题,因为当我在构造函数中调用它时,它会按预期工作。 我不知道除了使用线程之外,还能如何让我的函数等待 120 毫秒。还有其他选择吗? 提前致谢!

最佳答案

I don´t know how else i can make my function wait for 120ms besides using threads.

您没有使用线程。您正在当前线程中执行 run 方法。

如果你想在新线程中运行它,你需要类似的东西:

new Thread(snake).start();

关于java - 为什么我的 run() 方法没有从我的 Actionlistener 中正确调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31453322/

相关文章:

java - 数组列表初始化显示为 boolean 值

java - 智能卡和 p12 文件创建

javascript - JSHint 和 eclipse 插件

java - Eclipse Java 版本错误

multithreading - Julia - worker 找不到功能

java - 如何使用 Java 从 URL 链接获取 xsp 值

java - MyBatis 是如何处理空结果集的?

java - 如何从后台以编程方式恢复 Android Activity

python - PYQT - 如何使用取消按钮取消 GUI 中的循环?

c# - 如何从一个线程使用 Console.ReadLine 并从另一个线程使用 ConsoleKeys?