gpt4 book ai didi

java - 动态 JPanel 错误

转载 作者:行者123 更新时间:2023-12-02 02:54:00 25 4
gpt4 key购买 nike

我有 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com