我正在模拟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;
}
}
当我同时单击两个箭头时,超人返回。
最佳答案
同时按下两个键时,每个键都会调用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());
}
希望这可以帮助。