1

I created an array of buttons in java containing 9 buttons like this

JButton []button = new JButton[9];

When I try to access any of them later like

body.add(button[0]);    or 
body.add(button[1]);

it return the following error

Exception in thread "main" java.lang.NullPointerException   at
 java.awt.Container.addImpl(Container.java:1095)    at
 java.awt.Container.add(Container.java:415)     at
 Tic_Tac_Main.main(Tic_Tac_Main.java:105)  
BUILD SUCCESSFUL (total time: 4 seconds)

Note: body is a panel in which I'm adding button But it also end with a message BUILD SUCCESSFUL.

What is wrong in the code?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Inzimam Tariq IT
  • 6,548
  • 8
  • 42
  • 69
  • 2
    See [What is a stack trace, and how can I use it to debug my application errors?](http://stackoverflow.com/q/3988788/418556) & [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/q/218384/418556) – Andrew Thompson Sep 24 '15 at 18:29
  • 1
    Don't assume that if code compiles, then that means that it's correct. Even though you have BUILD SUCCESSFUL, you've still got a NPE that gets thrown when you try to use items in an array that have not yet been initialized. Your problem is similar to trying to make omelet using an empty egg carton. The egg carton must first be filled with eggs before you can take the carton out of the refrigerator, and use the eggs to make an omelet. – Hovercraft Full Of Eels Sep 24 '15 at 18:31
  • thank you @HovercraftFullOfEels – Inzimam Tariq IT Sep 24 '15 at 18:35

2 Answers2

4

When I try to access any of them later like

You won't succeed because you just declared the array and never added items into it. I mean you need to initialize them before use.

For ex :

button[0]= new JButton(); // creating and assigning a button at  0 position
body.add(button[0]);   // now accessing it.
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
3
JButton[] button = new JButton[9];

here you are only declare the array of buttons.

if you do something like button[0] this, you need to initialize your button before that you are accessing it. otherwist it will be null. that means some where you need to do

button[0] = new JButton()
subash
  • 3,116
  • 3
  • 18
  • 22