java.lang.NullPointerException error message

406 Views Asked by At
ImgSet[0] = new ImageIcon("bandeira-portugal.png",
                            "Portugal");
ImgSet[1] = new ImageIcon("south_korea-32.png",
                            "South_Korea");
ImgSet[2] = new ImageIcon("China-icon.png",
                            "China");
ImgSet[3] = new ImageIcon("Japan.png",
                            "Japan");    

This is my code for the image icons. I am getting the error message "java.lang.NullPointerException"! Can you please tell me how to fix it? My picture files are in the program folder!

Yes I did set the variable ImgSet if that's got anything to do with it.

private Icon[] ImgSet;
3

There are 3 best solutions below

0
On BEST ANSWER

Initialize your array first. Thats all:)

private Icon[] ImgSet = new Icon[4];

Remember that you cannot change arrays length, after you initialize it, so select a good size, in this example it is 4. If your collection is dynamic (you will add more elements, depending on runtime), change it to list, or set. Remember that arrays are fast, but their size is not editable.

1
On

You're just declaring ImgSet variable by doing:

private Icon[] ImgSet;

To initialize you should do something like:

private Icon[] ImgSet = new Icon[n];

Where n should be an initialized int or Integer.

You may way to use something like ArrayList or LinkedList instances from the java.util package.

0
On

Maybe you forget to initialize your array before.

Try this

ImageIcon[] ImgSet = 
{
   new ImageIcon("bandeira-portugal.png", "Portugal"),
   new ImageIcon("south_korea-32.png", "South_Korea"),
   new ImageIcon("China-icon.png", "China"),
   new ImageIcon("Japan.png","Japan")
};

Doubts: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html