我试图制作一个简单的游戏,我需要检查是否按下了多个键。类似的问题得到了以下答案:
class MultiKeyPressListener implements KeyListener {
// Set of currently pressed keys
private final Set<Character> pressed = new HashSet<Character>();
@Override
public synchronized void keyPressed(KeyEvent e) {
pressed.add(e.getKeyChar());
if (pressed.size() > 1) {
// More than one key is currently pressed.
// Iterate over pressed to get the keys.
}
}
@Override
public synchronized void keyReleased(KeyEvent e) {
pressed.remove(e.getKeyChar());
}
@Override
public void keyTyped(KeyEvent e) {/* Not used */ }
}
}
我如何&#34;迭代按下来获取密钥&#34;?我想出了以下内容:
// declarations
private final Set<Character> pressed = new HashSet<>();
// code
@Override
public synchronized void keyPressed(KeyEvent e) {
pressed.add(e.getKeyChar());
if(pressed.contains(KeyEvent.VK_UP)) {
switch(e.getKeyCode()) {
case KeyEvent.VK_LEFT:
starfighter.moveUpLeft();
break;
case KeyEvent.VK_RIGHT:
starfighter.moveUpRight();
break;
}
}
}
但这不起作用。我怎样才能做到这一点?
由于
答案 0 :(得分:2)
怎么样:
class MultiKeyPressListener implements KeyListener {
// Set of currently pressed keys
private final Set<Integer> pressed = new HashSet<Integer>();
@Override
public synchronized void keyPressed(KeyEvent e) {
pressed.add(e.getKeyCode());
if (pressed.contains(KeyEvent.VK_UP)) {
if (pressed.contains(KeyEvent.VK_LEFT)) {
starfighter.moveUpLeft();
}
if (pressed.contains(KeyEvent.VK_RIGHT)) {
starfighter.moveUpRight();
}
}
}
@Override
public synchronized void keyReleased(KeyEvent e) {
pressed.remove(e.getKeyCode());
}
@Override
public void keyTyped(KeyEvent e) {/* Not used */ }
}
}
注意如何使用一组整数而不是字符并存储密钥代码而不是关键字符。