-1

i use this command to add an image icon :

iadd.setIcon(new ImageIcon(getClass().getResource("add.png")));
top.add(iadd);

but i got that exception [Exception in thread "main" java.lang.NullPointerException]

4

4 回答 4

0

The possibilities to get nullpointerException is iadd is not initialized.

iadd.setIcon(new ImageIcon(getClass().getResource("add.png")));

or in the line

top.add(iadd);

top is not initialized.

于 2013-04-15T14:11:44.707 回答
0

We need more information to be able to help you correctly. However make sure you instantiate iadd and top.

To instantiate, you normally use the keyword new. You should have something like that ABOVE your lines:

X iadd = new X(...); // Probably ImageIcon in your case
Y top = new Y(...); // Probably some kind of List (ArrayList, LinkedList, etc.)

Since we don't know the types, X and Y and only placeholders ;)

于 2013-04-15T14:21:08.127 回答
0

I am on the feeling that your exception is comming from getClass().getResource("add.png")

It's possible the resource is not found in the current package?

于 2013-04-15T14:23:36.357 回答
0

I figured the reason out, it was because i forgot to validate the imageicon after defining it :

iadd.setIcon(new ImageIcon(getClass().getResource("add.png")));
validate();
top.add(iadd);
于 2013-07-21T12:32:38.100 回答