I created a JPanel
with a subpanel inside it using the GUI-designer of IntelliJ. Now I want the subpanel to be a new JPanel and readd to my top panel. But this causes a NullPointerExceptiion
. Why and how can I solve it? Note: None of my components are marked as "Custom Create"
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)
View Class
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>
Main
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);
}
}