我正在用Java模拟超人飞行。
如何制作同时考虑右箭头键和左箭头键的事件?
我设置了每个箭头的事件,如下所示:
public void keyPressed(KeyEvent e)
{
int KeyCode=e.getKeyCode();
switch(KeyCode)
{
case KeyEvent.VK_LEFT:
supermanleft.moveLeft();
break;
case KeyEvent.VK_RIGHT:
supermanfly.moveRight();
break;
case KeyEvent.VK_UP:
superman.moveUp();
break;
case KeyEvent.VK_DOWN:
superman.moveDown();
break;
}
}
当我同时点击两个箭头时,超人会回来。
答案 0 :(得分:0)
当按下两个键时,每个键都会调用keyPressed
。您可以按下一组按键,然后查看是否按下了两个按键:
private Set<Character> pressed = new HashSet<Character>();
public synchronized void keyPressed(KeyEvent e) {
pressed.add(e.getKeyChar());
if (pressed.size() > 1) {
//check if pressed contains what you want it to contain
} else {
//only one key is pressed - act as normal
}
}
public synchronized void keyReleased(KeyEvent e) {
//don't forget to remove when released:
pressed.remove(e.getKeyChar());
}
希望这有帮助。