Simon Tamás
Simon Tamás

Reputation: 281

Switching JPanels and keyListeners

I am developing a game, where you first get to the main screen, there are multiple selections to go, for example, Singleplayer, Twoplayer, Credits, etc.

I have one big problem. If I click a button in the menu, (not JButton) the JPanels switch, but the keyListener is lost. The Keylistener is in the same class as the game code, which implements JPanel. I tried everything to get the Keylistener to work, but it just won't.

Here is how the things are called: Main class --> Menu --> Game. I tried adding the keylistener to the main class, but it's not working.

So, JPanel switching is ok, but the Keylisteners are gone. I was developing the game before with new JFrames, so when I clicked a menu, a new frame was created. I didn't insert a code here, because it's too long (2000+ lines), and the KeyListener is working, but only when it is in a new JFrame. I set the mode int in the Menu class, by clicking a button.

This is currently my panel switch:

public void setJPanel() {
     switch (mode) {
        case 1:
            getContentPane().add(s);
            validate();
            break;
        case 2:
            getContentPane().removeAll();
            getContentPane().add(sp);
            validate();
            break;
    }
}

Thanks for your help in advance!

Upvotes: 1

Views: 1186

Answers (3)

Ahmed Magdy
Ahmed Magdy

Reputation: 1

Try using myPanel.requsetFocusInWindow(); before using setVisible(true);

Upvotes: 0

Patrick M
Patrick M

Reputation: 387

Cardlayout actually is screwy while refocusing.

@op, try calling requestFocusInWindow() after the new jpanel was added

Upvotes: 2

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Rather than use a KeyListener, have you given thought to or tried using Key Bindings? KeyListeners require that the component being listened to has focus, and focus may be lost for many reasons, especially when swapping views (are you using a CardLayout for this?). Key Bindings on the other hand can be set to be responsive even if the bound component doesn't have focus but when it is only held within a window that has focus. Tutorial: Using a CardLayout

Edit
I see that you're not using a CardLayout, and I suggest that you use this as it can make your view swapping cleaner and easier.

Edit 2
I agree that you don't want to post your entire 2000+ line program here as no one will have the time to read it, but consider condensing your question/problem into a single small class that is compilable and runnable by any and all of us, and demonstrates your problem. In other words, a Short, Self Contained, Compilable, Example or SSCCE .

Remember, the code should be compilable and runnable for many of us to be able to understand it fully.

Upvotes: 2

Related Questions