private class KeyHandler implements KeyEventDispatcher{
@Override
public boolean dispatchKeyEvent(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_RIGHT){
tetrominoList.get(currentPiece).moveRight();
}else if(e.getKeyCode() == KeyEvent.VK_LEFT){
tetrominoList.get(currentPiece).moveLeft();
}else if (e.getKeyCode() == KeyEvent.VK_UP){
System.out.print("k");
tetrominoList.get(currentPiece).rotate();
}
return false;
}
当我按向上箭头一次时,此代码返回“kk”。如何配置java或我的计算机,以便它只注册一个键击而不是两个?
编辑:这是我的临时解决方案
private class KeyHandler implements KeyEventDispatcher{
int counter = 0;
public boolean dispatchKeyEvent(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_RIGHT){
tetrominoList.get(currentPiece).moveRight();
}else if(e.getKeyCode() == KeyEvent.VK_LEFT){
tetrominoList.get(currentPiece).moveLeft();
}else if (e.getKeyCode() == KeyEvent.VK_UP){
counter++;
if(counter == 2){
System.out.print("k");
tetrominoList.get(currentPiece).rotate();
counter = 0;
}
}
答案 0 :(得分:1)
我可能错了,但看起来您的代码会同时处理KEY_PRESSED
和KEY_RELEASED
个事件。您可能应该检查KEY_TYPED
事件,一旦发生这种情况,请打印您的信件。否则,您只能处理前两个事件中的一个。