Switching JPanels and keyListeners

后端 未结 2 1249
走了就别回头了
走了就别回头了 2021-01-25 04:24

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 p

相关标签:
2条回答
  • 2021-01-25 04:32

    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.

    0 讨论(0)
  • 2021-01-25 04:38

    Cardlayout actually is screwy while refocusing.

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

    0 讨论(0)
提交回复
热议问题