动态JPanels错误

时间:2017-04-13 09:10:23

标签: java swing jpanel layout-manager cardlayout

我hava CardLayout并希望更换面板。为此我写了我的JFrame类:

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

你能告诉我我做错了吗?

1 个答案:

答案 0 :(得分: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的好例子。