2014-09-21 45 views
2

我有一个简单的swing应用程序,它带有一个包含各种组件的JFrame。在JFrame上我有一个扩展JPanel的自定义工具栏类。在JPanel上,我计划添加带图像图标的按钮。我的目录结构如下:从jar文件中加载图像(使用Eclipse IDE)

  • 项目/ src目录/ GUI(包适用于应用程序的源文件)
  • 项目/ src目录/图片(包包含一个jar文件jlfgr-1_0.jar与按钮图标和/或单独的图像文件)

问题是我想避免将单个图像文件复制到图像包。我宁愿只是直接从jar文件加载图像。我有私人的方法,返回适当的图标。此方法适用,例如,如果我拖动图像文件的图像包和呼叫:

button.setIcon(createIcon("/images/Save16.gif")); 

private ImageIcon createIcon(String path) { 
    URL url = getClass().getResource(path); 
    ImageIcon icon = new ImageIcon(url); 

    if(url == null) { 
     System.err.println("Unable to load image: " + path); 
    } 
    return icon; 

我知道这是基本的,但我怎么能直接得到我的图片来自jar文件在我目前的设置? 谢谢。

+0

可能重复http://stackoverflow.com/questions/6373621/loading-images-from-jars-for-swing-html ) – Smutje 2014-09-21 17:25:55

+0

该代码*已经*从应用程序类路径加载图像的方式,我们将从Jar加载资源! – 2014-09-21 23:34:00

回答

1

您可以从流中读取的图像,这得益于javax.imageio.ImageIO

private ImageIcon createIcon(String path) { 
    BufferedImage image = ImageIO.read(getClass().getResourceAsStream(path)); 
    ImageIcon icon = new ImageIcon(image); 
    return icon; 
} 
0

这是另一种方式。的图像是在位置src/images

BufferedImage myPicture = null; 
try { 
    myPicture = ImageIO.read(this.getClass().getResource("images/Picture2.png")); 
} catch (IOException e) { 
    // TODO Auto-generated catch block 
    try { 
     myPicture = ImageIO.read(this.getClass().getResource("images/broken_image.jpg")); 
    } catch (IOException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 
} 
JLabel picLabel = new JLabel(new ImageIcon(myPicture)); 
panel.add(picLabel); 
[从摇摆HTML罐加载图像(的