2012-03-17 84 views
1

我正在使用Eclipse,我希望将一些图像与我的.jar一起导出到“img”源文件夹中,以便它们显示在JAR中。用我的JAR文件导出图像

我的层次结构是:

项目>来源>包装> FILE.java

然后在项目被称为另一个源文件夹:

IMG> IMAGE.png

我目前使用以下方式链接到图像:

lblNewLabel_1.setIcon(new ImageIcon("img/logo1.png")); 

而且工作正常,直到我将其导出。

我将它导出为带有Extract required libraries的Runnable JAR文件,因为中间的文件不允许打开.jar文件。提取允许它打开,但图像不显示。

回答

1

当您在JAR中加载数据时,路径不一样。

您可以使用此方法时,你从一个JAR运行加载图像:

/** 
    * Create an instance of ImageIcon with the given path 
    * @param path String - path of the image 
    * @return ImageIcon - ImageIcon made with the image at the given path 
    */ 
private ImageIcon createImageIcon(String path) { 
    if (path != null) { 
     URL tmp = getClass().getResource(path.replace("\\", "/")); 
     if(tmp!=null) 
      return new ImageIcon(tmp); 
     else 
      return new ImageIcon(); 
    } else { 
     System.err.println("Couldn't find file: " + path); 
     return null; 
    } 
} 
+0

当我这样做,然后调用它像这样:lblNewLabel_1.setIcon(createImageIcon(“logo1.png”)); 它不显示图像 – user1176922 2012-03-17 11:59:20

+0

无论我使用什么路径,图像都会拒绝显示。 – user1176922 2012-03-17 12:04:45

+0

Ofc,图像与您的java文件不在同一目录中。如果你的“img”目录与你的“src”目录在同一个地方。我想你可以试试../../img/logo1.png。我不是100%确定你比我更了解你的文件层次结构;) – 2012-03-17 12:05:40