我正在使用这个简单的2.5D游戏,但我的键似乎无法切换。在主类中调用它时,在if语句中放置println语句没有运行,这不是问题。谢谢。
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class InputHandler implements KeyListener {
public InputHandler(Game game) {
game.addKeyListener(this);
}
public class Key {
private boolean pressed = false;
private int numTimesPressed = 0;
public boolean isPressed() {
return pressed;
}
public int getnumTimesPressed() {
return numTimesPressed;
}
public void toggle(boolean isPressed) {
pressed = isPressed;
if (isPressed()) {
numTimesPressed++;
}
}
}
// *This is where your keys go.
public Key up = new Key();
public Key down = new Key();
public Key left = new Key();
public Key right = new Key();
public void keyPressed(KeyEvent e) {
toggleKey(e.getKeyCode(), true);
}
public void keyReleased(KeyEvent e) {
toggleKey(e.getKeyCode(), false);
}
public void keyTyped(KeyEvent e) {
}
public void toggleKey(int keyCode, boolean isPressed) {
if (keyCode == KeyEvent.VK_W) {
up.toggle(isPressed);
}
if (keyCode == KeyEvent.VK_S) {
down.toggle(isPressed);
}
if (keyCode == KeyEvent.VK_A) {
left.toggle(isPressed);
}
if (keyCode == KeyEvent.VK_D) {
right.toggle(isPressed);
}
}
}
KeyListener
的问题是,当它注册到的组件是可聚焦的并且有焦点时,它只会通知你关键事件。
默认情况下,许多容器是不可聚焦的。
你实际上更好地使用键绑定
你可以看看我正在尝试让球逐渐移动的例子