0

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.

6
  • Have you initialised box? Commented Apr 5, 2014 at 11:42
  • for a quick reply check if your box is initialised. you should post your complete error log here for us to track the null pointer. Commented Apr 5, 2014 at 11:44
  • final JLabel[] box= new JLabel[27]; I initialised it like that is there any problem? Commented Apr 5, 2014 at 11:47
  • 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 Commented Apr 5, 2014 at 11:49
  • This probably has nothing to do with your problem, but do note that j is always equal to 1, so all icons will be initialized from "case1.png". Commented Apr 5, 2014 at 12:04

1 Answer 1

2

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++;
 }
Sign up to request clarification or add additional context in comments.

1 Comment

thanx :) it work but I found the problem. in for loop instead of i<25 i should do i<26 :DDDDD

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.