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?

3
  • 2
  • 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. Commented Sep 24, 2015 at 18:31
  • thank you @HovercraftFullOfEels Commented Sep 24, 2015 at 18:35

2 Answers 2

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.
Sign up to request clarification or add additional context in comments.

Comments

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.