简体   繁体   中英

Null Pointer Exception at JLabel Array

I want to create JLabel with icon in for loop.

Here is my code;

 final JLabel[] box = new JLabel[27]; 
 for(int i = 0; i < 25; i++){
     int j = 1;
     String r = "case" + j + ".png";
     box[i] = new JLabel(new ImageIcon(getClass().getResource(r)));
     j++;
 }

names of icons are like case1.png , case2.png ;....

But there is a null point exception.

Exception in thread "main" java.lang.NullPointerException at 
java.awt.Container.addImpl(Unknown Source) at java.awt.Container.add(Unknown Source)
at Game.<init>(Game.java:185) at Game.main(Game.java:243) here are the exceptions

Is it just because I did not create names of icons truely? Thanks in advance.

You are declaring ALL your JLabel 's name as case1.png since at the start of your for loop , you are assigning int j = 1;

Your code should look like this:

 final JLabel[] box = new JLabel[27]; 
 int j = 1; //should be outside the for loop
 for(int i = 0; i < 25; i++) {
     String r = "case" + j + ".png";
     box[i] = new JLabel(new ImageIcon(getClass().getResource(r)));
     j++;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM