Search code examples
javaswingillegalargumentexceptioncardlayout

CardLayout error: wrong parent for card layout


I have used cardlayout for one of my classes, however it is showing an error.

My code runs similar to this:

// panels instantiated
CardLayout cl = new CardLayout();
panel1.setLayout(cl);
panel2.setLayout(cl);

panel1.add(new JLabel("0 0"), "0");
panel1.add(new JLabel("0 1"), "1");

panel2.add(new JLabel("1 0"), "0");
panel2.add(new JLabel("1 1"), "1");

add(panel1);
add(panel2);

cl.show(panel1, "0");
cl.show(panel2, "0");  // error at this line

Why is it not considering panel2 as a parent container (IllegalArgumentException)?

Any help would be appreciated. Thanks.


Solution

  • CardLayout is not a layout that can be shared among containers and you should add the CardLayout to one container only. If you need two containers using the layout, give each its own CardLayout object.