Joe
Joe

Reputation: 100

KeyEvent not firing when certain other keys are pressed

I'm having more key problems in Java. The SPACE Key event works just fine by itself, and when other keys are being pressed...

But if I press down the UP key and the LEFT key at the same time the SPACE event does not fire. However the SPACE does fire when if LEFT or UP are pressed alone or with other keys.

Here's my code:

public void keyPressed(KeyEvent e) 
{
    if(e.getKeyCode() == KeyEvent.VK_UP)
    {
        upkeyisdown = true;         
    }
    if(e.getKeyCode() == KeyEvent.VK_DOWN)
    {
        downkeyisdown = true;
    }
    if(e.getKeyCode() == KeyEvent.VK_LEFT)
    {
        leftkeyisdown = true;
    }
    if(e.getKeyCode() == KeyEvent.VK_RIGHT)
    {
        rightkeyisdown = true;
    }
    if(e.getKeyCode() == KeyEvent.VK_SPACE)
    {
        spacekeyisdown = true;
    }

}  
public void keyReleased(KeyEvent e) 
{
    if(e.getKeyCode() == KeyEvent.VK_UP)
    {
        upkeyisdown = false;            
    }

    if(e.getKeyCode() == KeyEvent.VK_DOWN)
    {
        downkeyisdown = false;
    }
    if(e.getKeyCode() == KeyEvent.VK_LEFT)
    {
        leftkeyisdown = false;
    }
    if(e.getKeyCode() == KeyEvent.VK_RIGHT)
    {
        rightkeyisdown = false;
    }
    if(e.getKeyCode() == KeyEvent.VK_SPACE)
    {
        spacekeyisdown = false;
    }
}  

Upvotes: 2

Views: 1437

Answers (1)

trashgod
trashgod

Reputation: 205785

As noted in KeyEvent, there is no support for multiple simultaneous KEY_PRESSED or KEY_RELEASED events. The same applies to KeyStroke. You can bind to instances of KeyStroke that include modifiers, as shown here. Modifiers may include "alt, shift, control, meta, altGraph, or a combination thereof."

Addendum: "If I press down the UP key and the LEFT key at the same time, the SPACE event does not fire."

Using the KeyEventDemo from How to Write a Key Listener, I see the expected KEY_PRESSED and KEY_RELEASED events. The order varies because the events can't actually occur "at the same time," although KEY_PRESSED reliably precedes KEY_RELEASED. I suspect a logic error elsewhere in your code. One way to manage the complexity is to

  • Use an enum to hold keyCodes; this game uses single keystrokes, but it illustrates how to use an an enum in this context.

  • Use EnumSets to contain recognized combinations; there's a related example here.

Upvotes: 3

Related Questions