Reputation: 131
Im trying to do the quick following:
lblNewLabel.setIcon(new ImageIcon(ItemDialog.class.getResource("/items/" + items.get(seed).getImage())));
however I am getting Null Pointer exception in the above line.
The program is running fine when I am using it in following manner.
lblNewLabel.setIcon(new ImageIcon(ItemDialog.class.getResource("/items/item10312344.jpeg")));
it works.
EDIT: seed is the index number (1 in this case). items.get(1).getImage() holds the value of item10312344.jpeg but as above I get a null exception. but if manually input it, it works
what do I need to do to make this not get a null exception by getting it from the item list?
Upvotes: 0
Views: 121
Reputation: 133
Try to validate the object before calling "getImage"
//FIRST OF ALL: Make sure "items" is not null
if(items != null && items.get(seed) != null){
ItemDialog itemDialog = ItemDialog.class.getResource("/items/" + items.get(seed).getImage())
if(itemDialog != null)
lblNewLabel.setIcon(new ImageIcon(itemDialog));
}
/*I am not sure about of which type is the object items is carrying, but a more
decent approach would be*/
if(items != null){
"ObjectThatItemsIsCarrying" obj = items.get(seed);
//Checking if you got the image name
if(obj != null)
ItemDialog itemDialog = ItemDialog.class.getResource("/items/" + obj.getImage());
//Cheking if you got the image
if(itemDialog != null)
lblNewLabel.setIcon(new ImageIcon(itemDialog));
}
Upvotes: 1
Reputation: 985
Put the path in a string and use the string in the getResource method.
String path = "/items/" + item.get(seed).getImage();
Upvotes: 0