2015-06-21 202 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

相關問題