问题
I have a problem with the CardLayout show method
So I declare my CardLayout and apply it to my JPanel
CardLayout cl = new CardLayout();
panel.setLayout(cl);
Then I add a 2 panels into the CardLayout
cl.addLayoutComponent(panel, "menuScreen");
cl.addLayoutComponent(panel1, "gameScreen");
I then have a JButton that when is clicked, I show the gameScreen
public void mouseClicked(MouseEvent e) {
if(e.getSource() == (startGame))
scenechange.show(panel,"gameScreen");
}
The only problem is that it doesn't go to my gameScreen. It gives me an llegalArgumentException. It says "Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: wrong parent for CardLayout".
Thanks in advance
回答1:
You need to have three panels. The parent and the two cards.
Currently you have "panel" as the parent and one of the childen.
CardLayout cl = new CardLayout();
panel.setLayout(cl);
and
cl.addLayoutComponent(panel, "menuScreen");
Consider this code sample from the Java trail
....
//Create the "cards".
JPanel card1 = new JPanel();
card1.add(new JButton("Button 1"));
JPanel card2 = new JPanel();
card2.add(new JTextField("TextField", 20));
//Create the panel that contains the "cards".
cards = new JPanel(new CardLayout());
cards.add(card1, BUTTONPANEL);
cards.add(card2, TEXTPANEL);
来源:https://stackoverflow.com/questions/12290609/java-cardlayout-show-illegalargumentexception