我使用IntelliJ的GUI设计器创建了一个包含子面板的
JPanel
。现在我想让子面板成为一个新的JPanel
并重新添加到我的顶层面板中。但是这会引起一个NullPointerExceptiion
。为什么会出现这种情况,我该如何解决?注意:我的所有组件都没有标记为“自定义创建”。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(){
}
}
View.form
<?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);
}
}
panel.remove(subPanel);
这一行(从堆栈跟踪中很明显)。subpanel
或panel
在哪里实例化?3)对于这些类型的情况通常:使用CardLayout
,如此答案所示。 - Andrew Thompsonpanel.add(subpanel)
。 2.2) 我觉得如果我不勾选“自定义创建”,我就不需要手动实例化组件了吧?至少以前我从来没有这个需求...为什么在这里需要呢?在构造函数中实例化似乎解决了问题,但是在createUIComponents()
中勾选“自定义创建”并实例化却没有。但问题是,我将不得不通过编程的方式重新创建整个用户界面。ImageIcon
的JLabels
。