Question

I've made a game that is controlled by the arrow keys. Therefore I have a KeyListener listening for the arrow keys:

public void keyReleased(KeyEvent event)
{
    switch(event.getExtendedKeyCode())
    {
        case KeyEvent.VK_UP:
            gameManager.up();
            break;
        case KeyEvent.VK_DOWN:
            gameManager.down();
            break;
        case KeyEvent.VK_RIGHT:
            gameManager.right();
            break;
        case KeyEvent.VK_LEFT:
            gameManager.left();
            break;
    }
}

Now here is my problem:
When I maximize the window using the keyboard by pressing Windows key + Up arrow, these events still get fired. How can I detect that the Windows key has been pressed, while one of the arrow keys got pressed?

Was it helpful?

Solution

Set an flag in your KeyListener, e.g.

boolean windowsPressed;

public void keyPressed(KeyEvent e) {
    if(event.getExtendedKeyCode() == VK.WINDOWS) windowsPressed = true;
}

public void keyReleased(KeyEvent event)
{
    switch(event.getExtendedKeyCode())
    {
        case KeyEvent.VK_UP:
            if(!windowsPressed) gameManager.up();
            break;
        case KeyEvent.VK_DOWN:
            gameManager.down();
            break;
        case KeyEvent.VK_RIGHT:
            gameManager.right();
            break;
        case KeyEvent.VK_LEFT:
            gameManager.left();
            break;
        case KeyEvent.VK_WINDOWS:
            windowsPressed = false;
            break;
    }
}

OTHER TIPS

You can catch the window key in your keyreleased

case: KeyEvent.VK_WINDOWS:
//do nothing

so it wont register the up button when you pressed the window + up

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top