[英]Java - Game thread freezes when switching panels in CardLayout
I'm working on a 2D game in Java, using no libraries. 我正在使用Java开发2D游戏,没有使用任何库。
In my games InputHandler (used for movement, quitting, etc,.), when I press "Escape," the button to switch to the pause menu, and then hit the "Back" button, my player can no longer move. 在我的游戏InputHandler(用于移动,退出等)中,当我按“ Escape”(退出)时,该按钮切换到暂停菜单,然后单击“ Back”(返回)按钮,则我的玩家无法再移动。
PausePanelGUI: PausePanelGUI:
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);
}}
Escape button in InputHandler: InputHandler中的转义按钮:
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();
}
}
Pause and Resume methods: 暂停和恢复方法:
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 method: 运行方法:
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;
}
}
}
Any help? 有什么帮助吗? :3
:3
I fixed it simply by adding requestFocus();. 我只是通过添加requestFocus();来解决它。 The thread wasn't actually freezing, my InputHandler just wasn't being registered.
线程实际上并没有冻结,我的InputHandler尚未被注册。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.