2017-04-13 16 views
0

私はCardLayoutを使用しており、パネルを変更したいと思っています。そのために私は私のJFrameクラスを書いた:Dynamic JPanelsエラー

public class GUI_NewList extends javax.swing.JFrame { 

CardLayout layout = new CardLayout(); 

public GUI_NewList() { 
    initComponents(); 
    this.setLayout(layout); 

    JPanel paChoose = new Choose(); 

    layout.addLayoutComponent(paChoose, "1"); 
    layout.show(paChoose, "1"); 
} 

クラスが選択:

public class Choose extends JPanel { 

    public Choose() { 
     setLayout(new GridLayout(3, 1)); 

     JButton btnPractice = new JButton("Practice"); 
     add(btnPractice); 

     JButton btnNewList = new JButton("Create a new List"); 
     add(btnNewList); 

     JButton btnEditList = new JButton("Edit a List"); 
     add(btnEditList); 
    } 
} 

私はこれを実行すると、私はエラーを取得する:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: wrong parent for CardLayout 

あなたは私が持っているものを教えてもらえます間違っている?

+0

すぐに役立つようにするには、[MCVE]または[ショート、自己完結型、正しい例](http://www.sscce.org/)を投稿してください。 –

答えて

2

ここに問題を解決するMCVEがあります。問題の詳細については、コードコメントを参照してください。

import java.awt.*; 
import javax.swing.*; 

public class GUI_NewList extends JFrame { 

    CardLayout layout = new CardLayout(); 

    public GUI_NewList() { 
     this.setLayout(layout); 
     this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 

     JPanel paChoose = new Choose(); 

     // this only adds it to the layout, not the container. 
     layout.addLayoutComponent(paChoose, "1"); 
     // this adds it to the container (the content pane) 
     add(paChoose); 
     // the container of interest is the content pane. 
     layout.show(this.getContentPane(), "1"); 

     pack(); 
     setVisible(true); 
    } 

    public static void main(String[] args) { 
     Runnable r =() -> { 
      new GUI_NewList(); 
     }; 
     SwingUtilities.invokeLater(r); 
    } 
} 

class Choose extends JPanel { 

    public Choose() { 
     setLayout(new GridLayout(3, 1)); 

     JButton btnPractice = new JButton("Practice"); 
     add(btnPractice); 

     JButton btnNewList = new JButton("Create a new List"); 
     add(btnNewList); 

     JButton btnEditList = new JButton("Edit a List"); 
     add(btnEditList); 
    } 
} 

注:JFrameまたはJPanelのいずれかを拡張するため、ここでは良い場合がありません。