Reputation: 4151
I got null pointer exception during content adding in JFrame
in Swing.
public static void createAndShowGUI() {
//Create and set up the window.
frame = new JFrame("Data Entry Application");
//Set up the content pane.
// frame = new JFrame();
addComponentsToPane(frame.getContentPane()); // null pointer exception in this line
}
public static void addComponentsToPane(Container pane) {
if (RIGHT_TO_LEFT) {
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}
Border blackline, raisedetched = null, loweredetched,
raisedbevel = null, loweredbevel, empty, orangeline, redline, greenline, blueline;
blackline = BorderFactory.createLineBorder(Color.black);
orangeline = BorderFactory.createLineBorder(Color.ORANGE);
redline = BorderFactory.createLineBorder(Color.RED);
greenline = BorderFactory.createLineBorder(Color.GREEN);
blueline = BorderFactory.createLineBorder(Color.blue);
JButton button;
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
if (shouldFill) {
//natural height, maximum width
c.fill = GridBagConstraints.HORIZONTAL;
}
/* Header Section start*/
/* Username and designation starts */
JPanel p_username = new JPanel();
p_username.setMinimumSize(new Dimension(140, 30));
l_username = new JLabel(Login.login_username);
l_designation = new JLabel("Data Entry User");
JPanel t9 = new JPanel(new GridLayout(0, 1));
t9.add(l_username);
t9.add(l_designation);
t9.setPreferredSize(new Dimension(140, 30));
p_username.add(t9);
c.fill = GridBagConstraints.NORTH;
c.gridx = 0;
c.gridy = 0;
c.ipady = 25;
c.insets = new Insets(0, 10, 0, 0);
pane.add(p_username, c);
/* Username and designation end */
}
Suggest some idea.
Upvotes: 0
Views: 1699
Reputation: 6168
I mocked your addComponentsToPane()
method to show you what the problem is:
private static void addComponentsToPane(Container container)
{
System.out.println("Is container null? " + container == null);
JPanel panel = null;
container.add(panel);
}
Calling this method results in the following output:
false
Exception in thread "main" java.lang.NullPointerException
at java.awt.Container.addImpl(Container.java:1091)
at java.awt.Container.add(Container.java:415)
at FrameDemo.addComponentsToPane(FrameDemo.java:33)
at FrameDemo.createAndShowGUI(FrameDemo.java:25)
at FrameDemo.main(FrameDemo.java:14)
If you read the Javadoc, the getContentPane()
method does not return null as you can see from the resulting output. My second line declares a JPanel but does not instantiates the object, which I then try to add to the contents pane. This is causing the NullPointerException
in my case.
My conclusion: You are adding a component to the container that has not been properly instantiated. In fact, if you read the Javadoc for the Container.add(comp)
method, it states that this method throws a NullPointerException
if comp
is null. Check all of the components you are trying to add to it and you can figure out the rest.
Upvotes: 1