[英]getResources() for ImageIcon - java
我的第一個問題:
幾天來我一直試圖弄清楚這一點,但我到了失去耐心的地步。 以下是一些代碼和我的項目結構。
問題:如何讓getResources()
在 eclipse 中工作並在導入 jar 后工作?
謝謝您的幫助。
public enum Icons {
XXX("src/resoruces/icons/xyz.png");
private ImageIcon icon;
Icons(String path) {
try {
// will fail miserably in eclipse and after exporting to jar
URL imageURL = getClass().getClassLoader().getResource(path);
icon = new ImageIcon(imageURL);
} catch (Exception e) {
// works like a char in eclipse and after creating the jar file
// with the files in the same directory
System.out.println("getResoruce() did not work");
icon = new ImageIcon(path);
}
}
通常,從 Eclipse 導出 JAR 文件時,導出
src\/resources<\/code>的內容減去<\/em>
src<\/code>路徑名本身。
要從您的 JAR 中加載圖像,您可以執行以下操作:
InputStream stream = getClass().getResourceAsStream("/resources/icons/xyz.png");
ImageIcon icon= new ImageIcon(ImageIO.read(stream));
如果 png 文件已打包到 JAR 中與它們在原始 src 目錄中相同的位置,則
XXX("resources/icons/xyz.png");
src<\/code>目錄在類路徑中不可用
InputStream imageInputStream = getClass().getClassLoader().getResourceAsStream("resources/icons/xyz.png");
byte[] imageData = org.apache.commons.io.IOUtils.toByteArray(in)
ImageIcon imageIcon = new ImageIcon(imageData, "description about image");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.