0
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;
        }
    }
4

1 回答 1

1

我可能错了,但看起来您的代码同时处理了KEY_PRESSED事件KEY_RELEASED。可能你应该检查一个KEY_TYPED事件,一旦发生,打印你的信。否则,您只能处理前两个事件之一。

于 2013-05-18T19:32:11.087 回答