我真的很難過。我只是一個試圖撰寫一個小的 Java 程式的老 C X11/Motif 程式員。在閱讀了一周的 Oracle Java 檔案以及與 getResource 相關的 Stack Overflow 答案后,我仍然無法弄清楚如何在我的 jar 檔案中檢索圖示檔案的路徑。
我的圖示包含在我的應用程式的 jar 檔案中。我希望使用 jar 檔案中的相對位置來訪問它們。我假設最好的方法是通過 getResource 方法。
我的程式代碼的核心部分稱為F?d(發音為 food - 就像漫畫“ Get Fuzzy ”中的貓一樣)如下:
package localhost.system1;
imports not shown for brevity.
public class Fud extends JPanel
implements FocusListener, ActionListener, ItemListener
{
private static final long serialVersionUID = 1L;
static Food data = null;
static int prev = 0;
static int next = 1;
static int plus = 2;
static int minus = 3;
public static void main(String args[]) throws Exception
{
LocalDate now = LocalDate.now();
int dateDifference = 0;
// load in the existing data
data = new Food(programName);
data.loadFood(programName);
// test to see if data is up to date. Add days if not
dateDifference = Math.abs((int)ChronoUnit.DAYS.between(now, data.day[0].date));
if ( dateDifference != 0)
{
data.adjustToToday(dateDifference, programName);
}
/////////////////////////////////////////////////
// create the GUI and switch running over to it.
/////////////////////////////////////////////////
Fud fud = new Fud();
Class<? extends Fud> fudClass = fud.getClass();
String className = fudClass.getName();
System.out.println("fudClass getname returns " className);
URL testURL = fudClass.getResource("prev.png");
System.out.println("fudClass getResource returned " testURL);
// Create GUI and turn the control over to it
javax.swing.SwingUtilities.invokeLater
(new Runnable()
{
public void run()
{
URL[] iconURL = new URL[4];
iconURL[prev] = Fud.class.getResource("prev.png");
iconURL[next] = Fud.class.getResource("next.png");
iconURL[plus] = Fud.class.getResource("plus.png");
iconURL[minus] = Fud.class.getResource("minus.png");
createAndShowGUI(fud, iconURL);
}
}
);
} // end of main
.
.
.
Rest of methods and subroutines needed
.
.
.
}
運行時,代碼回傳以下結果:
fudClass getname returns localhost.system1.Fud
fudClass getResource returned null
這讓我很沮喪。無論我嘗試什么(我已經嘗試了很多事情),結果都是一樣的。對于 getResource 方法的回應,我不斷收到 NULL。當我查詢 jar 檔案時,jar -tf Fud.jar我得到以下資訊:
jar tf Fud.jar
META-INF/MANIFEST.MF
localhost/
localhost/system1/
localhost/system1/Day.class
localhost/system1/Food.class
localhost/system1/Fud$1.class
localhost/system1/Fud$2.class
localhost/system1/Fud$3.class
localhost/system1/Fud$4.class
localhost/system1/Fud$5.class
localhost/system1/Fud$6.class
localhost/system1/Fud$7.class
localhost/system1/Fud.class
minus.png
next.png
plus.png
prev.png
所以圖示在 Jar 檔案中。誰能告訴我我做錯了什么?在 Eclipse 中,我的專案資源管理器看起來像:eclipse Project Explorer
我在eclipse中將Image目錄添加到我的專案Java構建中,如下所示:Eclipse Java Build
我使用 Eclipse Version: 2021-12 (4.22.0) Build id: 20211202-1639 構建了程式。此外,我在 Windows 11 Pro build 22000.434 上使用 Java 17.0.1 2021-10-19 LTS。
uj5u.com熱心網友回復:
您必須在資源前面添加一個斜杠:
Fud.class.getResource("/prev.png");
否則java在類所在的同一檔案夾中搜索,
所以它會搜索localhost/system1
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/421040.html
標籤:
上一篇:嘗試將LWJGL2與Eclipse一起使用時出現不滿意的鏈接錯誤
下一篇:試圖以升序反轉我的流-Java8
