我有一个添加了jpanel1的jframe。 jpanel1就像Gameview。如果用户想要暂停,则可以按esc键,然后将显示jpanel2。在那里,他可以按一个按钮以返回jpanel1。
Presser.value变量是视图的状态。
也许我在理解编译器如何运行代码方面是错误的。
Presser.value=0 means->player is in game
Presser.value=1 means->player paused game
Presser.value=2 means->player pressed button and variable need reset to 0, after resumed to game.
为了测试,我为游戏中的简历添加了关键的“空格”。这可行。而且我可以切换无限的视图(这应该是这样的)
我只有在使用按钮时才有问题。
public class Window extends JFrame{
private JPanel jPanel1 = new JPanel1();
private JPanel jPanel2 = new JPanel2();
private Timer t;
Presser presser = new Presser();
public Window(){
add (jPanel1);
pack();
setVisible(true);
addKeyListener(keyboardListener);
tester();
}
private final KeyAdapter keyboardListener = new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_ESCAPE:
add (jPanel2);
remove (jPanel1);
pack();
setVisible(true);
Presser.value=1;
break;
case KeyEvent.VK_SPACE:
add (jPanel1);
remove (jPanel2);
pack();
setVisible(true);
Presser.value=0;
break;
}
}
};
public void tester(){
Timer timer = new Timer();
timer.schedule( new TimerTask() {
public void run() {
System.out.println(Presser.value);
if (Presser.value==2){
add (jPanel1);
remove (jPanel2);
Presser.value=0;
pack();
setVisible(true);
timer.cancel();
timer.purge();
return;
}
}
}, 0, 1000);
}
}