IntelliJ gui creator: JPanel gives runtime null pointer exception upon adding any component

kevin948 picture kevin948 · Mar 9, 2012 · Viewed 7.1k times · Source

I am having a problem with IntelliJ's java gui creation. Most of the code behind the panel is unfortunately hidden within the gui creator and not editable by me.

I created a blank JPanel "questionPanel" with the ItelliJ GridLayoutManager. When I try to add anything to that panel, I get a null pointer exception even though the panel is definitely not null. I also tried adding a JTextField to the layout (out of curiosity) and that did not help either. The JTextField shows up, but I still cannot add anything from within the code.

When I change the layout manager to anything else (GridBagLayout, FormLayout, BorderLayout, etc.), I no longer get errors, but nothing shows up.

DisplayView.java

private JPanel questionPane;

public void initialize()
{
    questionPane.addMouseListener(new MouseListener() {

        @Override
        public void mouseReleased(MouseEvent e) {
            questionPane.add(new JLabel("Test"));
            System.out.println("Click event received.");
        }
        //other overrides hidden
}

Does anybody have an idea of what is going on behind the scenes or a way for me to get components onto the panel? Thanks.

Sample Stack Trace (this trace is not made by the same code as above, but it is the same error):

Exception occurred during event dispatching:
java.lang.NullPointerException

at com.intellij.uiDesigner.core.GridLayoutManager.addLayoutComponent(
GridLayoutManager.java:134)

at java.awt.Container.addImpl(Container.java:1074)
at java.awt.Container.add(Container.java:365)
at [MyProject].UI.View.DisplayView$1.actionPerformed(DisplayView.java:91)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
.....

Answer

kevin948 picture kevin948 · May 15, 2012

For anybody who is using IntelliJ's GUI creator and receiving the same error, I fixed the problem by manually setting the panel's layout manager in the code instead of choosing different layout managers within the GUI creator.

Example:

questionPane.setLayout(new BoxLayout(questionPane, BoxLayout.PAGE_AXIS));