-1

I would like to know, what is main by NullPointerException.

My understanding of this error code is that there is a variable with null value being used. But what does it really mean. Kindly seek your enlightenment.

Exception in thread "main" java.lang.NullPointerException

at java.awt.Container.addImpl(Unknown Source)

at java.awt.Container.add(Unknown Source)

at TicTacToe.<init>(TicTacToe.java:29)

at TicTacToe.main(TicTacToe.java:49)

public class TicTacToe {

JPanel t3pan;
JButton button1;
JButton button2;
JButton button3;
JButton button4;
JButton button5;
JButton button6;
JButton button7;
JButton button8;
JButton button9;

TicTacToe()
{
    t3pan = new JPanel();

    GridLayout gl = new GridLayout(3,3);
    t3pan.setLayout(gl);

      t3pan.add(button1);
      t3pan.add(button2);
      t3pan.add(button3);
      t3pan.add(button4);
      t3pan.add(button5);
      t3pan.add(button6);
      t3pan.add(button7);
      t3pan.add(button8);
      t3pan.add(button9);


    JFrame t3frame = new JFrame();

    t3frame.setContentPane(t3pan);
    t3frame.pack();
    t3frame.setVisible(true);
}

public static void main(String[] args)
{
    new TicTacToe();
}

}
splrs
  • 2,404
  • 2
  • 16
  • 28
lonelearner
  • 1,049
  • 3
  • 11
  • 21
  • 4
    dont see any of those buttons initialized anywhere – Reimeus Dec 27 '14 at 18:07
  • The method *add throws NullPointerException* if *param* is *null*. [API doc](http://docs.oracle.com/javase/7/docs/api/java/awt/Container.html#add%28java.awt.Component%29) – sergioFC Dec 27 '14 at 18:10
  • Negative vote for not looking at the API docs before posting question. – sergioFC Dec 27 '14 at 18:12
  • Thank you! Was careless on my part for not initialising. But finally learn and understand one of the cause of nullpointerexception. And thanks for the API, but if there is no one to enlighten, will still not understand just by looking at it. http://docs.oracle.com/javase/7/docs/api/java/awt/Container.html#add%28java.awt.Component%29 – lonelearner Dec 27 '14 at 18:53

2 Answers2

3

button1 through button9 are null (they have no value). You declared them, but you never instantiated them. You need something like,

JButton button1 = new JButton("Button 1"); //<-- for all 9.

The default value for a class field

JButton button1;

is null, so that is equivalent to

JButton button1 = null;
Elliott Frisch
  • 183,598
  • 16
  • 131
  • 226
3

The button variables are null because of which the lines t3pan.add(button1) and so on are failing with NullPointerExceptions.

You need to initialize the button variables before adding them to t3pan.

Invisible Arrow
  • 3,925
  • 2
  • 21
  • 29