Java-在CardLayout中切换面板时游戏线程冻结
我正在用Java开发一个2D游戏,不使用库 在我的游戏Puthandler(用于移动、退出等)中,当我按下“退出”按钮切换到暂停菜单,然后按下“后退”按钮时,我的玩家无法再移动 PausePanelGUI:Java-在CardLayout中切换面板时游戏线程冻结,java,multithreading,Java,Multithreading,我正在用Java开发一个2D游戏,不使用库 在我的游戏Puthandler(用于移动、退出等)中,当我按下“退出”按钮切换到暂停菜单,然后按下“后退”按钮时,我的玩家无法再移动 PausePanelGUI: public class PausePanelGUI extends JPanel { public PausePanelGUI(LayoutManager layout, Game game) { super(layout); JButton backBtn = new
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);
}}
InputHandler中的Escape按钮:
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;
}
运行方法:
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我只是通过添加requestFocus()来修复它;。线程实际上没有冻结,我的InputHandler只是没有注册。你的播放器输入代码是什么样子的?您是否尝试过调试它,以查看在取消游戏暂停后按按键时是否调用它?我没有,我将测试它,并发布输入代码。编辑:取消暂停后未调用我的密钥:0我尚未阅读您的代码,但我认为您不应该使用CardLayouts(因为swing会干扰图形等)。while(isRunning).不在(我希望如此)?我不知道为什么暂停/恢复功能是同步的,因为它应该只从EDT调用。