Skip to content
Advertisement

java swing nullpointer exeption whilst adding buttons [duplicate]

solution

So i was trying to do a java-swing-gui for a school project and therefor I have to add 72 Buttons (idk) to a JPanel element. I tried using a for-loop:

JavaScript

but it didnt really work out and threw a nullPointerExeption. Any suggestions?

Here is the full code:

JavaScript

Advertisement

Answer

When you create an array like this:

JavaScript

that array is empty. In other words, even though that array has the capacity to keep 72 buttons, it doesn’t have those buttons yet, you have to add them manually, like this:

JavaScript

But if you don’t, fields[i] will be null by default, and so when you try to do field.setSize(20, 20), that field is null and will cause a NullPointerException.

Primitive arrays also have default values. For example elements of an array of int are all 0, and elements of an array of boolean are all false. The same is true for non-primitive arrays (like JButton), the elements are all by default null.

Your final code would look something like this:

JavaScript

or:

JavaScript

or even shorter:

JavaScript

Also consider turning that 72 into a constant (a static final field).

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement