Intellij, "contentPane cannot be set to null" using swing designer

Quinn picture Quinn · Feb 11, 2018 · Viewed 7.8k times · Source

I'm trying out intellij, and am trying to do some swing development. I am running into an issue I have never experienced on eclipse, and I am wondering if I have something set up wrong.

Here is my GUI class that is run by my driver:

package view;

import javax.swing.*;
import java.awt.*;

public class View {

private JPanel panel;

public void run() {
    JFrame frame = new JFrame("Vending Machine");
    frame.setContentPane(new View().panel);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}

{
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
    $$$setupUI$$$();
}

/**
 * Method generated by IntelliJ IDEA GUI Designer
 * >>> IMPORTANT!! <<<
 * DO NOT edit this method OR call it in your code!
 *
 * @noinspection ALL
 */
private void $$$setupUI$$$() {
    final JPanel panel1 = new JPanel();
    panel1.setLayout(new GridBagLayout());
}

}

as far as I can tell, my run() method is as straightforward as it gets. However, upon compiling, this is the error I receive:

Exception in thread "main" java.awt.IllegalComponentStateException: contentPane cannot be set to null.
at javax.swing.JRootPane.setContentPane(JRootPane.java:621)
at javax.swing.JFrame.setContentPane(JFrame.java:698)
at view.View.run(View.java:13)
at model.VendingMachine.<init>(VendingMachine.java:14)
at controller.Driver.main(Driver.java:14)

For whatever reason, the intellij autocreated code that does not properly initialize the JPanel, which is why it's null.

I've tried instantiating it myself inside run (panel = new JPanel();) but that has not helped.

Is this something obvious? I've never run into this issue when getting started with swing in eclipse.

Answer

konmal88 picture konmal88 · Feb 11, 2018

You are setting as JFrame' s content pane the panel 'panel' but the JPanel you are creating is called 'panel1'. To fix this problem change JPanel' s name to 'panel' instead of 'panel1'.