我试着快速跟进:
lblNewLabel.setIcon(new ImageIcon(ItemDialog.class.getResource("/items/" + items.get(seed).getImage())));
但是我在上面的行中得到Null Pointer异常。
当我以下列方式使用它时程序正常运行。
lblNewLabel.setIcon(new ImageIcon(ItemDialog.class.getResource("/items/item10312344.jpeg")));
它有效。
编辑:种子是索引号(在这种情况下为1)。 items.get(1).getImage()保存item10312344.jpeg的值,但如上所述,我得到一个null异常。但是如果手动输入它,它就会起作用
我需要做些什么才能通过从项目列表中获取它来使其无法获得null异常?
答案 0 :(得分:1)
在调用“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));
}
答案 1 :(得分:0)
将路径放在字符串中并使用getResource方法中的字符串。
String path = "/items/" + item.get(seed).getImage();