gpt4 book ai didi

java - 将新的 JPanel 添加到另一个 JPanel 中会导致 NullPointerException

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

我使用 IntelliJ 的 GUI 设计器创建了一个 JPanel,其中包含一个子面板。现在我希望子面板成为一个新的 JPanel 并重新添加到我的顶部面板。但这会导致 NullPointerException。为什么以及如何解决它?注意:我的组件都没有标记为“自定义创建”

Exception in thread "main" java.lang.NullPointerException
at com.intellij.uiDesigner.core.GridLayoutManager.addLayoutComponent(GridLayoutManager.java:134)
at java.awt.Container.addImpl(Container.java:1127)
at java.awt.Container.add(Container.java:417)
at View.<init>(View.java:16)
at Main.main(Main.java:4)

查看类

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
public class View{
private JPanel panel;
private JPanel subPanel;

public JPanel getPanel() {
return panel;
}

View()
{
panel.remove(subPanel);
subPanel = newPanel();
panel.add(subPanel);
}
JPanel newPanel(){
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
JLabel label = new JLabel("test");
panel.add(label);
return panel;
}

private void createUIComponents(){
}
}

查看表单

<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="View">
<grid id="27dc6" binding="panel" layout-manager="GridLayoutManager" row-count="2" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="20" y="20" width="500" height="400"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<grid id="860ea" binding="subPanel" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children/>
</grid>
<vspacer id="7838f">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
</vspacer>
</children>
</grid>
</form>

主要

import javax.swing.*;
public class Main {
public static void main(String[] args) {
View view = new View();
JFrame frame = new JFrame("Window");
frame.setContentPane(view.getPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}

最佳答案

GridLayoutManager (IntelliJ) 似乎不允许在不先手动实例化 JPanel 的情况下添加新组件。更改为 GridBagLayout 解决了问题。

关于java - 将新的 JPanel 添加到另一个 JPanel 中会导致 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44313029/

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