这是CardTesting类,我得到了IllegalArgumentException:CardLayout的错误父级。行cl.show(this,“Panel 2”)抛出一个IllegalArgumentException:CardLayout的错误父级。请帮忙! :d
table
}
答案 0 :(得分:0)
您收到IllegalArguementException
,因为您在显示卡片this
时使用的是cl.show(this, "Panel 2");
,其中this
指的是父母的JFrame
为父'JFrame'添加了任何布局。总是一种更好的方法将卡封装在JPanel
而不是JFrame
您必须将两张卡/面板添加到父面板,并将布局指定为cardLayout
。在此我创建了一个cardPanel
作为父级
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();
}
}