Switching JPanels and keyListeners

半城伤御伤魂 提交于 2019-12-20 04:23:46

问题


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!


回答1:


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.




回答2:


Cardlayout actually is screwy while refocusing.

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



来源:https://stackoverflow.com/questions/8187447/switching-jpanels-and-keylisteners

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!