I'm making and testing a swing application using key listeners and CardLayout. I have two JPanels that can respond to key events; one counts and displays the number of key presses so far, the other displays what key was last pressed. I only want one of these panels visible at a time, and I want key presses to only affect the visible panel.

I contain these two panels in a third JPanel that uses a CardLayout. This panel itself has a key listener to switch between the panels it's containing. I stick this panel in a JFrame for the final application.

What I'm trying to do in general is make a JPanel that acts as a container for two other JPanels, only showing one at a time. If I press a certain key, like SPACE for example, the contained panels are switched so that the hidden one is visible and the visible one is hidden. If some other key is pressed, I want that key to affect and be processed by the visible panel, but not the hidden one.

I sort of having it work the way I want right now, except I have to press TAB a lot. When I'm flipping between the two "inner" panels I have to press TAB before my key presses affect it. I have to press TAB again to be able to flip between my two inner panels again.

If anyone can give me some tips I'd be appreciative.

Thank you,

Aaron J. M.