我如何使我的逃离键暂停和恢复游戏时,它被按两次?我已经尝试调用键适配器类在我的线程类,但它只暂停游戏;它不会恢复它。
下面是暂停游戏的代码://the thread class
class recMove extends Thread {
JFrame b;
public boolean running=true;
//public boolean gameover=false;
public recMove(JFrame b){
this.b=b;
pauseGame();
}
public void run(){
while(running){
b.repaint();
try {
Thread.sleep(100);
} catch(InterruptedException e){}
}
}
public void pauseGame(){
addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e) {
int keyCode=e.getKeyCode();
if(keyCode==KeyEvent.VK_ESCAPE) {
running=false;
System.out.println("escape pressed");
}
if(keyCode==KeyEvent.VK_END){
System.exit(0);
}
}
});
}
}
它不会恢复,因为线程已被杀死,当您按转义时,running
值被设置为false
,因此此循环:
while(running){
b.repaint();
try {
Thread.sleep(100);
} catch(InterruptedException e){}
}
将结束,这将使run()
方法退出。当扩展Thread
(或实现Runnable
)的类的run()
方法退出时,线程被杀死,因此没有更多的监听您的按键。
你需要改变你的run()
逻辑,所以当running
被设置为false
时,它不会退出,而是等待下一次按键或在其他地方添加监听器(在不同的线程中),所以它会再次创建一个新的线程。
此外,在你的逻辑esc
只将running
更改为false,如果你想要它然后恢复游戏,你应该检查running
的状态,如果它是false
,你应该将其设置为true
。