[SOLVED] CardLayout Help
In my JPanel classes I have keyListeners checking for certain keyPressed() events. However, after I switch from my first view to a second one I get no keyPressed responses. Any ideas on why this is? Does setFocusable() get set to false or something?
public class Layout extends JFrame
/** Create instances of our panels */
final StartMenu start = new StartMenu(this);
final GameBoard game = new GameBoard(this);
final ContactInfo contact = new ContactInfo(this);
final HighScores scores = new HighScores(this);
final UpgradeMenu upgrade = new UpgradeMenu(this);
final InstructionMenu instructions = new InstructionMenu(this);
CardLayout myLayout = new CardLayout();
/** Set the layout and add the menus. Assign them names */
add(start, "Start Menu");
add(contact, "Contact Information");
add(scores, "High Scores");
public void swapView(String name)
public static void main(String[ ] args)
Is there a way I can do it with default CardLayout? I'd rather not have to rely on a seperate subclass.
As I said in the link the basic solution is to add an AncestorListener to every panel. Then the AncestorListener can request focus on the panel as it is displayed.
There is no reason you can't create your own AncestorListener to do this (all you need is the first couple of lines of the ancestorAdded method). Then you manually add the listener to every panel before you add the panel to the card layout.
So I really only need this much:
of the ancestorAdded and a new AncestorListener() which checks for ancestorAdded() and reports to the Layout class?
public void ancestorAdded(AncestorEvent event)
currentCard = event.getComponent();
Do you have any idea why Cards are not focused by default in CardLayout?
Edit: Nevemind, figured it out. It's working great now. Thanks a lot! Marked as solved.