java - 动态 JPanel 错误

标签 java swing jpanel layout-manager cardlayout

我有 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");
}

类(class)选择:

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

你能告诉我我做错了什么吗?

最佳答案

这是一个解决该问题的 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 的好例子.

关于java - 动态 JPanel 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43388049/

相关文章:

java - 将 JMockit 模拟注入(inject) Spring 上下文

java - 如何为java和python设置bash路径

java - 如何让我的 MenuItems 从单独的类中调用方法?

java - 按钮最初不绘制

Java - 顶部的 GridBagLayout 组件在调整大小时消失

java - 重新验证 JPanel 的父框架

java - 如何在 Java 中实现行级安全性?

java - 如何在类中设置根据其他实例变量的值不断更新的实例变量?

java - 将对象添加到 Jpanel

java - 如何在不每次加载 URL 的情况下从 JPanel 调整子 WebView/JFXPanel 的大小?