Code compiles but gives error when I run it

ronald chu

Greenhorn

Posts: 16

posted 3 years ago

So I am finishing up a GUI that randomly rolls a dice and shows you the dice face from a file that I have on my computer. It compiles fine, but when I open the GUI and press the button "Roll" it gives me errors and does not display the images. Help please :\

These are the errors I get, I did go to the lines and try to fix them but when I changed the lines I either got the errors or nothing happening with the GUI.

And the way you have this coded will leak all kinds of memory, eventually starving out the JRE of available heap.

Matthew Brown

Bartender

Posts: 4568

9

posted 3 years ago

Hi Ronald. Welcome to the Ranch!

As Roger says, you haven't initialised your label. The error message gives you a lot of information about what's happening.
That tells you what the error is (NullPointerException) and exactly where it happened (line 46). That line is:
There's only one way that line can possibly throw a NullPointerException - if label is null. So the next thing to look at is, where do you initialise that variable?

ronald chu

Greenhorn

Posts: 16

posted 3 years ago

Roger Sterling wrote:The problem is label has not been initialized : NullPointer.

And the way you have this coded will leak all kinds of memory, eventually starving out the JRE of available heap.

Yeah, I'm still kind of new at this. But anyways I put the private static JLabel label; and diceRoll = new JLabel();

Ulf Dittmer

Rancher

Posts: 42972

73

posted 3 years ago

ronald chu wrote:I put the private static JLabel label;

That declares label, but doesn't assign anything to it, so it's null and can't be dereferenced.

ronald chu

Greenhorn

Posts: 16

posted 3 years ago

Matthew Brown wrote:Hi Ronald. Welcome to the Ranch!

As Roger says, you haven't initialised your label. The error message gives you a lot of information about what's happening.
That tells you what the error is (NullPointerException) and exactly where it happened (line 46). That line is:
There's only one way that line can possibly throw a NullPointerException - if label is null. So the next thing to look at is, where do you initialise that variable?

Ok so I initialized one label in the if(roll ==1) and the rest of those if statements and one in actionperformed. Where should I initialize the label?

ronald chu

Greenhorn

Posts: 16

posted 3 years ago

Ulf Dittmer wrote:

ronald chu wrote:I put the private static JLabel label;

That declares label, but doesn't assign anything to it, so it's null and can't be dereferenced.