I don't understand why I get an IllegalArgumentException: wrong parent for CardLayout

150 views Asked by At

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();
}

}

1

There are 1 answers

1
Madhan On BEST ANSWER

You are getting a IllegalArguementException because you are using this when showing the cards cl.show(this, "Panel 2"); where this refers to the JFrame the parent and you haven't added any Layout for the parent 'JFrame'.It's always a better approach to enclose the cards inside a JPanel rather than JFrame

You have to add to two cards/panels to a parent panel and assign the Layout as cardLayout.Here I have created a cardPanel as parent

import java.awt.*;
import javax.swing.*;

public class CardTesting extends JFrame {

    CardLayout cl = new CardLayout();

    JPanel panel1, panel2;
    JPanel cardPanel;
    public CardTesting() {
        super("Card Layout Testing");
        setSize(400, 200);
        this.setLayout(cl);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(cl);
        panel1 = new JPanel();
        panel2 = new JPanel();
        cardPanel=new JPanel();
        cardPanel.setLayout(cl);
        panel1.add(new JButton("Button 1"));
        panel2.add(new JButton("Button 2"));
        cardPanel.add(panel1, "Panel 1");
        cardPanel.add(panel2, "Panel 2");
        add(cardPanel);
        setVisible(true);
    }

    private void iterate() {
        /* the iterate() method is supposed to show the second card after Thread.sleep(1000), but cl.show(this, "Panel 2") throws an IllegalArgumentException: wrong parent for CardLayout*/
        try {
            Thread.sleep(1000);
        } catch (Exception e) {
        }
        cl.show(cardPanel, "Panel 2");
    }

    public static void main(String[] args) {
        CardTesting frame = new CardTesting();
        frame.iterate();
    }
}