Java 如何在不获取null异常的情况下将path放入变量中
我试着做以下几点:Java 如何在不获取null异常的情况下将path放入变量中,java,string,image,Java,String,Image,我试着做以下几点: lblNewLabel.setIcon(new ImageIcon(ItemDialog.class.getResource("/items/" + items.get(seed).getImage()))); 然而,我在上面的一行中得到了空指针异常 当我以以下方式使用程序时,程序运行良好 lblNewLabel.setIcon(new ImageIcon(ItemDialog.class.getResource("/items/item10312344.jpeg")));
lblNewLabel.setIcon(new ImageIcon(ItemDialog.class.getResource("/items/" + items.get(seed).getImage())));
然而,我在上面的一行中得到了空指针异常
当我以以下方式使用程序时,程序运行良好
lblNewLabel.setIcon(new ImageIcon(ItemDialog.class.getResource("/items/item10312344.jpeg")));
它起作用了
编辑:seed是索引号(本例中为1)。getItems.get(1).getImage()保存item10312344.jpeg的值,但如上所述,我得到一个null异常。但是如果手动输入,它会工作
我需要做什么才能通过从项目列表中获取该路径而不获取空异常?将路径放入字符串中,并在getResource方法中使用该字符串
String path = "/items/" + item.get(seed).getImage();
在调用“getImage”之前尝试验证对象
对不起,这是怎么回答的?你有信心它解决了OP的问题吗?不知道为什么,但我有一个类似的问题,它适用于完整的路径,但如果我试图将路径的部分缝合在一起,则不会。这对我来说很有用。你能把items.get(seed).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));
}