这是 CardTesting 类,我在其中得到 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
,因为您在显示卡片时使用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();
}
}