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]
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.
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 ;)
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?
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);