2010-03-06 67 views
10

我有一个带有工具栏的Java项目,工具栏上有图标。这些图标存储在名为resources /的文件夹中,因此例如路径可能为“resources/icon1.png”。此文件夹位于我的src目录中,因此编译时将该文件夹复制到bin中。我正在使用以下代码来访问资源。如何访问JAR文件中的资源?

protected AbstractButton makeToolbarButton(String imageName, String actionCommand, String toolTipText, 
     String altText, boolean toggleButton) { 

    String imgLocation = imageName; 
    InputStream imageStream = getClass().getResourceAsStream(imgLocation); 

    AbstractButton button; 
    if (toggleButton) 
     button = new JToggleButton(); 
    else 
     button = new JButton(); 

    button.setActionCommand(actionCommand); 
    button.setToolTipText(toolTipText); 
    button.addActionListener(listenerClass); 

    if (imageStream != null) { // image found 
     try { 
      byte abyte0[] = new byte[imageStream.available()]; 
      imageStream.read(abyte0); 

      (button).setIcon(new ImageIcon(Toolkit.getDefaultToolkit().createImage(abyte0))); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       imageStream.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } else { // no image found 
     (button).setText(altText); 
     System.err.println("Resource not found: " + imgLocation); 
    } 

    return button; 
} 

(imageName将是“resources/icon1.png”等)。这在Eclipse中运行时工作正常。但是,当我从Eclipse中导出可运行的JAR时,找不到图标。

我打开了JAR文件,资源文件夹就在那里。我试过了所有的东西,移动文件夹,改变JAR文件等,但我无法看到图标。

有谁知道我在做什么错? (作为一个侧面的问题,是否有任何文件监视器可以与JAR文件一起工作?当出现路径问题时,我通常只需打开FileMon以查看正在发生的事情,但在本例中它只是显示为访问JAR文件)

谢谢。

+1

所以5行代码加载图标比较好,然后是2行代码?当然要找出使用2行代码的秘密,你实际上必须自己做一些阅读。我猜这个秘密会隐藏起来。 – camickr 2010-03-06 22:55:02

回答

5

要从JAR资源利用加载图像下面的代码:

Toolkit tk = Toolkit.getDefaultToolkit(); 
URL url = getClass().getResource("path/to/img.png"); 
Image img = tk.createImage(url); 
tk.prepareImage(img, -1, -1, null); 
+0

Toolkit包含哪些内容? – tomasb 2012-08-07 10:02:29

+0

@tomasb java.awt.Toolkit – Christian 2012-08-16 16:17:16

10

我看到两个问题与您的代码:

getClass().getResourceAsStream(imgLocation); 

这假设图像文件在同一文件夹中的类此代码是从,而不是在一个单独的资源文件夹的.class文件。试试这个:

getClass().getClassLoader().getResourceAsStream("resources/"+imgLocation); 

另一个问题:

byte abyte0[] = new byte[imageStream.available()]; 

InputStream.available()返回流中的字节总数的方法!它返回无阻塞的可用字节数,通常少得多。

您必须编写一个循环才能将字节复制到临时ByteArrayOutputStream,直到到达流的末尾。或者,使用带有URL参数的getResource()createImage()方法。

4

来自How to Use Icons的Swing教程的部分向您展示了如何创建URL并在两条语句中读取图标。

0

例如,在NetBeans项目,建立src文件夹中的资源文件夹。把你的图像(jpg,...)放在那里。

无论您使用的ImageIO或工具包(包括的getResource),你必须包括前/在你的路径映像文件:

Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/resources/agfa_icon.jpg")); 
setIconImage(image); 

如果此代码是你的JFrame类里面,图像被添加到该框架作为标题栏中的图标。