2016-01-10 43 views
0

我正在使用Java开发2D游戏,不使用库。Java - 在CardLayout中切换面板时游戏线程会冻结

在我的游戏InputHandler(用于移动,退出等)中,当我按下“Escape”按钮切换到暂停菜单,然后点击“返回”按钮时,我的播放器不能再播放移动。

PausePanelGUI:在InputHandler

public class PausePanelGUI extends JPanel { 

public PausePanelGUI(LayoutManager layout, Game game) { 
    super(layout); 

    JButton backBtn = new JButton("Back"); 
    backBtn.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      try { 
       CardLayout c = new CardLayout(); 
       c = (CardLayout)(GameLauncher.getMainLauncherPanel().getLayout()); 
       c.show(GameLauncher.getMainLauncherPanel(), "Game"); 
       game.resume(); 
      } catch (Exception ex) { 
       ex.printStackTrace(); 
      } 
     } 
    }); 
    backBtn.setBounds(250, 200, 150, 25); 

    this.add(backBtn); 
}} 

退出按钮:

if (ke.getKeyCode() == KeyEvent.VK_ESCAPE) { 
     try { 
      CardLayout c = new CardLayout(); 
      c = (CardLayout)(GameLauncher.getMainLauncherPanel().getLayout()); 
      c.show(GameLauncher.getMainLauncherPanel(), "Pause"); 
      game.pause(); 
     } catch (Exception ex) { 
      ex.printStackTrace(); 
     } 
    } 

暂停和恢复方法:

public synchronized void resume() { 
    System.out.println("Game resumed!"); 
    this.isPaused = false; 
} 

public synchronized void pause() { 
    System.out.println("Game paused!"); 
    this.isPaused = true; 
} 

Run方法:

while (isRunning) { 
     if (!this.isPaused) { 
      long now = System.nanoTime(); 
      delta += (now - lastTime)/nsPerTick; 
      lastTime = now; 
      boolean shouldRender = true; 

      while (delta >= 1) { 
       ticks++; 
       update(); 
       delta -= 1; 
       shouldRender = true; 
      } 

      try { 
       Thread.sleep(2); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 

      if (shouldRender) { 
       frames++; 
       repaint(); 
      } 

      if (System.currentTimeMillis() - lastTimer >= 1000) { 
       lastTimer += 1000; 
       frames = 0; 
       ticks = 0; 
      } 
     } 
    } 

任何帮助? :3

+0

你的播放器输入代码是什么样的?您是否尝试过通过它进行调试,以查看在您取消暂停游戏后按键时是否调用了它? – Sam

+0

我没有,我会测试,以及后输入的代码。 编辑:我的钥匙没有被取消暂停后调用:0 – Xolitude

+0

我没有看过你的代码,但我认为你不应该使用CardLayouts(因为摆动干扰你的图形等)。 –

回答

0

我简单地通过添加requestFocus();来修复它。该线程并没有真正冻结,我的InputHandler只是没有被注册。