基本上,每次按下 F1 键时,我都会尝试切换布尔值。在我的主课中,我有每秒调用 60 次的更新方法,我编写了如下代码:
主类:
private Keyboard key = new Keyboard; // keyboard object
boolean debug; // boolean to control visibility of debug screen
private boolean toggle; // used to toggle boolean
private void update() { // update is called 60/s
if (key.isKeyPressed(Keyboard.f1) && !toggle) {
debug = !debug;
toggle = true;
} else if (!key.isKeyPressed(Keyboard.f1)) toggle = false;
}
键盘类:
public class Keyboard implements KeyListener {
private boolean[] keys = new boolean[65536];
public static final int f1 = KeyEvent.VK_F1; // key code of f1 key
public void keyPressed(KeyEvent e) {
keys[e.getKeyCode()] = true;
}
public void keyReleased(KeyEvent e) {
keys[e.getKeyCode()] = false;
}
public void keyTyped(KeyEvent e) {
}
public boolean isKeyPressed(int key) {
return keys[key];
}
这样它就可以完美运行,但是如果我在 Keyboard.class 中创建类似的方法,它就不起作用:
主类中的更新方法:
private void update() {
key.toggle(Keyboard.f1, debug); // toggle boolean debug if f1 key pressed, but.. NOT WORKING!! WHYYY!!?
}
键盘类:
private boolean toggle;
public void toggle(int key, boolean b) {
if (isKeyPressed(key) && !toggle) {
b = !b;
toggle = true;
} else if (!isKeyPressed(key)) toggle = false;
}
我的问题是: 为什么第二种方法不起作用,我该如何解决它? 谢谢!