我有一个带有工具栏的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文件)
谢谢。
所以5行代码加载图标比较好,然后是2行代码?当然要找出使用2行代码的秘密,你实际上必须自己做一些阅读。我猜这个秘密会隐藏起来。 – camickr 2010-03-06 22:55:02