我不明白为什么我会收到 IllegalArgumentException: wrong parent for CardLayout

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

这是 CardTesting class,我在其中得到 IllegalArgumentException:CardLayout 的父级错误。 cl.show(this, "Panel 2") 行抛出 IllegalArgumentException:CardLayout 的父级错误。请帮忙! :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();
}

}

你得到 IllegalArguementException 因为你在出示卡片 cl.show(this, "Panel 2"); 时使用 this 其中 this 指的是 JFrame parent 并且您还没有为 parent 'JFrame' 添加任何布局。将卡片封装在 JPanel 中总是比 JFrame[=20= 更好的方法]

您必须将两个 cards/panels 添加到 parent 面板并将布局指定为 cardLayout。这里我创建了一个 cardPanel 作为 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();
    }
}