Hi there,

I have this null pointer exception error in my code which I can't fix. I'm just trying to create an interface which can display an image, text and 12 buttons all at once. I've checked out loads of other threads, but I can't see where the Null entry is in my code?

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

public class PhoneInterface1 extends JFrame
{
	private JPanel imagePanel, numberPad;
	private JTextField text;
	
	public PhoneInterface1()
	{
		JButton[] buttons = new JButton[12];
		this.add("North", imagePanel);
		this.add("Centre", text);

		numberPad.setLayout(new GridLayout(4,3));
		for(int i=0; i<12; i++)
		{ 
			buttons[i] = new JButton(""+i);
			numberPad.add(buttons[i]);
		}
		this.add("South", numberPad);
		this.pack();
		this.setVisible(true); //displays the frame
	}
	public static void main(String args[])
	{
	   new PhoneInterface1();
	}
}

..and the error I'm getting is:

Exception in thread "main" java.lang.NullPointerException
at java.awt.Container.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at javax.swing.JFrame.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at PhoneInterface1.<init>(PhoneInterface1.java:14)
at PhoneInterface1.main(PhoneInterface1.java:29)

Can anyone spot the bug?

Ger.

I think that the

private JPanel imagePanel, numberPad;
private JTextField text;

have not been instatiated

Try:

private JPanel imagePanel = new JPanel();
private JPanel numberPad = new JPanel();
private JTextField text; = new JTextField();

If this does not fix your problem try to debug and see what is null

javaAddict is correct. You have not initialized the component variables.

The stack trace indicates this is occurring on line 14 in your constructor, so that is where you would want to look first to debug the error. Learning to read the stack traces will save you a lot of time and frustration in finding the errors in your program. It's well worth to the time to study them closely and look up the exception that it is reporting in the API documentation.

This article has been dead for over six months. Start a new discussion instead.