Search code examples
javakeypress

Handling two keypresses in java


I have a problem in my code, because i don't know how to make picture move diagonal when you press ARROW UP and ARROW LEFT at the same time, etc.. Here is my code:

 public void keyPressed(KeyEvent ke) {
    switch (ke.getKeyCode()) {
    case KeyEvent.VK_RIGHT: {
        cordX += 5;
    }
        break;
    case KeyEvent.VK_LEFT: {
        cordX -= 5;
    }
        break;
    case KeyEvent.VK_DOWN: {
        cordY += 5;
    }
        break;
    case KeyEvent.VK_UP: {
        cordY -= 3;
    }
        break;
    }
    repaint();
}

I don't know if this would work

case KeyEvent.VK_UP  &&  KeyEvent.VK_LEFT: {
        cordY += 5;
    }
        break;

Solution

  • If you are using Swing components, use the Key Bindings API, see How to Use Key Bindings, it will solve a rafter of issues...

    In any case, the solution is (basically) the same, what you need to do is define a series of flags which define which keys are currently pressed and at a regular interval update the state of the variables affected by those flags

    private boolean down, up, left, right;
    //...
    
    public void keyPressed(KeyEvent ke) {
        switch (ke.getKeyCode()) {
            case KeyEvent.VK_RIGHT:
                right = true;
                break;
            case KeyEvent.VK_LEFT:
                left = true;
                break;
            case KeyEvent.VK_DOWN:
                down = true;
                break;
            case KeyEvent.VK_UP:
                up = true;
                break;
        }
        updateState();
    }
    
    public void keyReleased(KeyEvent ke) {
        switch (ke.getKeyCode()) {
            case KeyEvent.VK_RIGHT:
                right = false;
                break;
            case KeyEvent.VK_LEFT:
                left = false;
                break;
            case KeyEvent.VK_DOWN:
                down = false;
                break;
            case KeyEvent.VK_UP:
                up = false;
                break;
        }
        updateState();
    }
    
    protected void updateState() {
        if (right) {
            cordX += 5;
        } else if (left) {
            cordX -= 5;
        }
        if (down) {
            cordY += 5;
        } else if (up) {
            cordY -= 3;
        }
        repaint();
    }
    

    You could then use a javax.swing.Timer to schedule a regular call back, which could be used to call updateState (instead of calling it from the key event handlers).

    Have a look at How to use Swing Timers for more details...