-
[SOLVED] CardLayout Help
Code:
import javax.swing.JFrame;
import java.awt.CardLayout;
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();
public Layout()
{
/** Set the layout and add the menus. Assign them names */
setLayout(myLayout);
add(start, "Start Menu");
add(game, "Game");
add(contact, "Contact Information");
add(scores, "High Scores");
add(upgrade, "Upgrades");
add(instructions, "Instructions");
setSize(500, 500);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
swapView("Start Menu");
}
public void swapView(String name)
{
myLayout.show(getContentPane(), name);
}
public static void main(String[ ] args)
{
new Layout();
}
}
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?
-
-
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:
Code:
public void ancestorAdded(AncestorEvent event)
{
currentCard = event.getComponent();
if (isRequestFocusOnCard)
currentCard.transferFocus();
of the ancestorAdded and a new AncestorListener() which checks for ancestorAdded() and reports to the Layout class?
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.