[英]Load images in jar file
我正在嘗試從可執行的JAR文件加載圖像。
這是檢索圖像的功能:
public static ImageIcon loadImage(String fileName, Object o) {
BufferedImage buff = null;
try {
buff = ImageIO.read(o.getClass().getResource(fileName));
// Also tried getResourceAsStream
} catch (IOException e) {
e.printStackTrace();
return null;
}
if (buff == null) {
System.out.println("Image Null");
return null;
}
return new ImageIcon(buff);
}
這就是它被稱為的方式:
logo = FileConverter.loadImage("/pictures/Logo1.png", this);
JFrame.setIconImage(logo.getImage());
這是一個簡單的對象。 我也沒有得到NullPointerException,除非它被UI掩蓋。
我檢查了JAR文件,圖像位於:
/pictures/Logo1.png
這個當前代碼既可以在eclipse中使用,也可以在導出到JAR並在終端中運行時使用,但在雙擊JAR時不起作用,在這種情況下,圖標是默認的JFrame圖標。
謝謝你的幫助。 可能只有我遺漏了一些明顯的東西。
我曾經遇到過類似的問題,結果卻發現了相關的問題以及我的路徑在某種程度上處於錯誤的位置。 我從我編寫的一些舊代碼中挖出這個代碼,使其使用絕對路徑。 這似乎解決了我的問題; 也許它會對你有用。
String basePath = (new File(".")).getAbsolutePath();
basePath = basePath.substring(0, basePath.length()-1);
FileConverter.loadImage(basePath+"/pictures/Logo1.png", this);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.