This is the CardTesting class where I get the IllegalArgumentException: wrong parent for CardLayout. The line cl.show(this, "Panel 2") throws an IllegalArgumentException: wrong parent for CardLayout. Please help! :D
import java.awt.*;
import javax.swing.*;
public class CardTesting extends JFrame {
CardLayout cl = new CardLayout();
JPanel panel1, panel2;
public CardTesting() {
super("Card Layout Testing");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(cl);
panel1 = new JPanel();
panel2 = new JPanel();
panel1.add(new JButton("Button 1"));
panel2.add(new JButton("Button 2"));
add(panel1, "Panel 1");
add(panel2, "Panel 2");
setVisible(true);
}
private void iterate() {
try {
Thread.sleep(1000);
} catch (Exception e) { }
cl.show(this, "Panel 2");
}
public static void main(String[] args) {
CardTesting frame = new CardTesting();
frame.iterate();
}
}
You are getting a
IllegalArguementException
because you are usingthis
when showing the cardscl.show(this, "Panel 2");
wherethis
refers to theJFrame
the parent and you haven't added any Layout for the parent 'JFrame'.It's always a better approach to enclose the cards inside aJPanel
rather thanJFrame
You have to add to two cards/panels to a parent panel and assign the Layout as
cardLayout
.Here I have created acardPanel
as parent