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)
.....
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));
I've filed the issue as a bug on the JetBrains website and received the following answer:
For fix NPE, please add a child component to a JPanel with GridLayoutManager with GridConstraints like this:
panel.add(new JLabel(), new GridConstraints(...))
or use other layout.
Using the GridConstraints solved the problem for me just as using another LayoutManager.
I shortened & edited the answer for readability
I got the same error as you did. I have a JPanel with Layout Manager set to GridLayoutManager Intellij. When I tried to add any component to this panel, I was getting the exception.
I then went into the GUI editor and changed to BorderLayout and everything worked fine. I am not sure why it isn't working for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With