這個問題已經有很多答案了。我也嘗試了很多。我還沒有找到解決方案。
我在我的專案中加載了一些影像(Swing - ImageIcons)。在運行對話框中,它們也都顯示在我的 GUI 中。但是編譯后程式根本無法啟動。錯誤訊息因程序而異。
最后,我嘗試簡單地加載 aFile
來列印絕對路徑。然后看起來像這樣:
File f = new File(Loadscreen.class.getResource("../../../../resources/materials/icon.png").getFile());
System.out.println(f.getAbsolutePath());
控制臺NullPointerException
為此回傳一個:
控制臺編譯:
Exception in thread "main" java.lang.NullPointerException
at de.franken.ration.gui.Loadscreen.<init>(Loadscreen.java:43)
at de.franken.ration.Rationboard.onEnable(Rationboard.java:84)
at de.franken.ration.Rationboard.main(Rationboard.java:75)
控制臺日食:
H:\Users\Hinrich\Documents\Java\Rationboard\bin\resources\materials\icon.png
在第 43 行,我定義了f
.
我的樹看起來像這樣:
Rationsboard
L_ src
L_ de
L_ franken
L_ ration
L_ gui
L_ Loadscreen.class
L_ resources
L_ materials
L_ icon.png
但是,該圖示包含在 JAR 中。
感謝所有回復的人。
//編輯:我玩了更多。只要要加載的資源在同一個包中,就可以加載。但是,如果我用 更改包../
,NullPointerException
就會出現。
uj5u.com熱心網友回復:
采用:
this.getClass().getResource("/resources/materials/icon.png");
請注意問題中看到的方法的兩個不同之處:
this.getClass()
將找到適合應用程式資源的背景關系類加載器。"/resources/materials/icon.png"
前導/
將告訴getResource
方法從類路徑或 Jar 的根目錄進行搜索。
順便說一句:任何時候都不要涉及檔案。getResource
回傳一個URL
并且 Jar 中的資源不能作為File
物件訪問。
uj5u.com熱心網友回復:
作為第一步,您可以通過運行來驗證圖示是否包含在 jar 中jar -tf file.jar
。
你有沒有嘗試過
File f = new File(Loadscreen.class.getResource("/materials/icon.png").getFile()); System.out.println(f.getAbsolutePath());
假設icon.png
在resources/materials
檔案夾中?
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/444771.html