Question

Ok so I have a JButton to restart my game.

private static class Clicked implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent event) {
        hero.setHealth(100);
        cl.show(cards, sGame);
    }
}

After I press the button the keyboard listener doens't work. I looked it up and it seems like the window is losing focus. I already have setfocusable and adding the keylistener in my game panel:

addKeyListener(new Keys());
setFocusable(true);
setDoubleBuffered(true);

Do I do something after the button event or what?

Was it helpful?

Solution

The window's not losing focus, the button is gaining focus, taking it away from your component with the KeyListener.

In your investigations, you should have also found out that KeyListener will only respond to key events when the component is focusable AND has focus. This is a known limitation of KeyListener...

Also in your investigations, you should have found that Key Bindings API is normally recommended as fix to this problem...

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