2015-06-21 115 views
0

这是CardTesting类,我得到IllegalArgumentException:CardLayout的父级错误。行cl.show(this,“Panel 2”)抛出一个IllegalArgumentException:CardLayout的父类错误。请帮忙! :d我不明白为什么我得到IllegalArgumentException:CardLayout的父级错误

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

}

+0

您可以附加堆栈跟踪吗? – AlexR

+0

这是你的问题吗? http://stackoverflow.com/questions/12290609/java-cardlayout-show-illegalargumentexception – alessiop86

回答

0

你得到一个IllegalArguementException因为你是显示卡cl.show(this, "Panel 2");其中thisJFrame父在使用this,你还没有添加父“任何布局的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(); 
    } 
} 
+0

非常感谢您的回复,并且我意识到为什么使用面板作为保管卡的容器更好。但我仍然不明白为什么它不能与JFrame一起工作,因为我确实调用了它的setLayout(cl)方法。 – andy

相关问题