Search code examples
javaswingintellij-ideaintellij-plugin

(IntelliJ GUI Designer) Runtime NullPointerException upon adding a component to a JPanel


Working on an IntelliJ plugin and trying to add a JLabel component to a JPanel on click on a JButton and this is a snippet of my code.

addLabelButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        contentPane.add(new JLabel("Hi, JLabel!"));
        contentPane.revalidate();
        contentPane.repaint();
    }
});

On click on the JButton I'm getting a run time error.

2020-01-02 17:44:16,118 [ 30502] ERROR - llij.ide.plugins.PluginManager - null java.lang.NullPointerException at com.intellij.uiDesigner.core.GridLayoutManager.addLayoutComponent(GridLayoutManager.java:134) at java.desktop/java.awt.Container.addImpl(Container.java:1152) at java.desktop/java.awt.Container.add(Container.java:436)


Solution

  • After a ton of researching, I've got the point. the problem is you can't add a component to a JPanel if the Layout Manager of the JPanel is equal to GridLayoutManager (IntelliJ).

    If you have the same problem:

    • Go to the GUI Designer
    • Select the JPanel that you want to add a component to it
    • From the properties panel, change the Layout Manager to anything but GridLayoutManager (IntelliJ) or FormLayout (JGoodies)

    IntelliJ GUI Designer properties panel
    IntelliJ GUI Designer properties panel

    Or programmatically

    contentPane.setLayout(new BoxLayout());