我有一個帶有工具欄的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