2

The title might be a little misleading, didnt know how to put my problem short.

Basically what im doing is im using keyboardlistener to find out which keys are down and according to that im moving my game character.

The problem is, when you click out of the window, while holding down a key my listener doesnt register the keyReleased event.

I tried to fix it by using mouse listener and the mouseExited event, but that doesnt fix it all the time, sometimes it does sometimes it doesnt.

Heres my implementation:

Keyboard:

public void mouseLeftWindow()
{
    for(int i =0;i<KEY_COUNT;i++)
    {
        keys[i] = false;
    }
}

@Override
public void keyPressed(KeyEvent e) 
{
    int keyCode = e.getKeyCode();
    if(keyCode>=0 && keyCode<KEY_COUNT)
    {
        keys[keyCode] = true;
    }
}

@Override
public void keyReleased(KeyEvent e) 
{
    int keyCode = e.getKeyCode();
    if(keyCode>=0 && keyCode<KEY_COUNT)
    {
        keys[keyCode] = false;
    }
}

where keys[] is a boolean[] describing, which codes are pressed

mouse:

@Override
public void mouseExited(MouseEvent e) 
{
    mouseMoved(e);
    keyboard.mouseLeftWindow();
}

1 Answer 1

2

Your program will listen for further key events even when your mouse exited the component. That means you set everything to false on exit but if a key is still pressed it will be set to true immediately again. I think you are looking for a FocusListener instead of a MouseListener.

    addFocusListener(new FocusListener() {

        @Override
        public void focusGained(FocusEvent e) {

        }

        @Override
        public void focusLost(FocusEvent e) {
            keyboard.mouseLeftWindow();
        }

    });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.