I'm trying to build a calculator. I have 4 classes, one of them is a ButtonsClass which holds an array of buttons. I want to use these buttons in my GUI class, so I can fill a gridlayout with the buttons by means of a for loop. I have made an Getter method in the ButtonsClass to get access from the GUI class, in the GUI class I call the button by the code buttonsclass.getButton(i));
When run the GUI class I get a nullpointer exception.
I think there is a problem with the getter method in the buttonsclass. Can you help me? I've worked for hours on this, Eclipse doesn't give any debug-feedback anymore, so I thought my code was finally ok, but when I run it I get the nullpointer exception.
Here is my code, I hope you can help me further.
And here is a part of the GUI class:
please cut here
A NullPointerException is usually easy to fix. Look at the stack trace for the exception. It tells you exactly in which line of code of which source file the exception happens. Go to that place and see what is null that isn't supposed to be null.
When you try to call a method or access a member variable using a reference that's null, you'll get a NullPointerException.
The code you posted doesn't seem to have any obvious statements that would produce an NPE.
Thanks for the quick reply, I get the npe in line 30 of the gui class. I think there is a problem with the getter method in the buttonsclass. Can you tell how you would call i.e. buttons and buttons[i] within the gui class from the buttonsclass?
in this code you didn't call getNumericButtons() which creates the buttons for you
so when you access the buttons you are getting null pointer exception..please make sure
you have called getNumericButtons() method....
Or create the array contents in the class constructor. That way you don't need the method, and you will be sure that all elements are initialized and nobody forgot to call getNumberButtons:
This also prevents anyone from calling getNumberButtons() twice, thereby creating a fresh new set of buttons. If that's still what you need, create a new instance of this class instead.
Patrick de Kruijf
Joined: Mar 02, 2010
I, uhm, we did it
I ran the cod again and now I got my calculator interface on my screen just like I planned out. I've tried every combination of constructors and getter method, but it wouldn't work all the time, but now it does just fine!
Thank you very much, now I can move on to my next problem, I hope I can fix this myself!