2013-06-06 23 views
0

我試着做快速以下情況:如何把路徑變量沒有得到空例外

lblNewLabel.setIcon(new ImageIcon(ItemDialog.class.getResource("/items/" + items.get(seed).getImage()))); 

但是我得到空指針異常上面一行。

當我按以下方式使用時,程序運行良好。

lblNewLabel.setIcon(new ImageIcon(ItemDialog.class.getResource("/items/item10312344.jpeg"))); 

它的工作原理。

編輯:種子是索引號(在這種情況下是1)。 items.get(1).getImage()保存item10312344.jpeg的值,但如上所示,我得到一個null異常。但如果手動輸入它,它的工作原理

我需要做些什麼才能使它不從項目列表中獲得它的空例外?

+0

你可以把代碼items.get(種子).getImage()。 – namalfernandolk

回答

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)); 
} 
0

將路徑放入字符串中,並在getResource方法中使用該字符串。

String path = "/items/" + item.get(seed).getImage(); 
+0

對不起,這是怎麼回事?你有信心解決OP的問題嗎? – Zong

+0

不知道爲什麼,但我有一個類似的問題,爲完整的路徑工作,但不是如果我試圖縫合部分路徑。這對我來說很有用。 –