How can I get keyboard input for a JPanel when it is not focused?

36 views Asked by At

I'm making a 2D role-playing game using Swing and AWT, and I'm pretty new to Java. I have a JPanel TunnelsPanel, which can switch between WorldPanel and CombatPanel. I want to have a mute function which would stop music from playing across the game, and not just specific to one panel. I want key input for the letter "m" to be taken from TunnelsPanel and toggle the boolean variable mute, which the children JPanels can check the value of and decide whether to play or not play music.

I tried using a KeyListener in TunnelsPanel to try and get input from TunnelsPanel, but since it was not focused, I could not get the input. I want world or combat panels to be focused so that the player can actually move the character around inside each panel. However, I also want a global KeyListener in TunnelsPanel that can toggle boolean mute no matter which panel is actually open, whether it be WorldPanel or CombatPanel.

0

There are 0 answers