我想加載一個圖像作爲我的應用程序中的圖標使用。根據本tutorial適當的方法是:使用getClass()加載資源getResource()
protected ImageIcon createImageIcon(String path, String description)
{
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
所以,我放置在文件的位置,並通過它作爲參數傳遞給該函數。這不起作用,即imgURL爲空。當我嘗試通過明確傳遞路徑創建ImageIcon時:
ImageIcon icon = new ImageIcon(path,"My Icon Image");
它工作得很好!因此,應用程序可以從明確定義的路徑中拾取圖像,但是沒有使用getResources()拾取圖像。在這兩種情況下,路徑變量的值都是相同的。爲什麼它不工作?如何通過類加載器找到資源?
謝謝。
您使用的是IDE嗎? IDE是否設置爲將資源複製到編譯到的類中? – z5h 2010-02-26 16:45:16
圖像位於相對於類和項目根目錄的位置? – willcodejavaforfood 2010-02-26 16:49:29
是的,我使用Eclipse,並沒有設置複製資源。已經修復了。該課程位於root/bin//MyClass,圖像位於root/resources/images/myImage.gif 感謝您的回覆。 –
Luhar
2010-02-26 16:51:50