Java - CardLayout show() IllegalArgumentException

ⅰ亾dé卋堺 提交于 2019-12-23 04:51:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!