我知道这是一个非常常见的错误,并且我已经阅读了几十篇关于此类错误的帖子,但由于某种原因,似乎完全没有解决问题。
我的最终目标是从项目文件夹中与 src 处于同一级别的特定位置(具体来说,数据文件夹)读取图像,并使用该图像创建一个按钮。但是,我似乎无法读取图像,并且一直为空。
此外,我已经尝试了所有我能想到的可能组合:
gitinit.png
//gitinit.png
\gitinit.png
/gitinit.png
\gitinit.png
数据/gitinit.png
数据//gitinit.png
数据\gitinit.png
数据\gitinit.png
一切都是出于纯粹、毫无意义的挫败感......
我正在使用 Eclipse。然而,该项目是用ant构建的。
这是我的项目的结构:
可以看出,我已经在所有可能的地方添加了 gitinit.png,但没有效果。
当我在某处读到时,我什至尝试将数据文件夹添加到构建路径中,但再次无望。
我意识到在这种情况下,“/data/gitinit.png”形式的绝对路径是理想的,但这是另一个问题。我正在研究的是一个处理工具。该工具在运行时从Processing 内部调用。当我运行时
System.out.println(this.getClass().getResource("/").getPath());
我得到以下输出:
/C:/Program%20Files/processing-2.1.1-windows64/processing-2.1.1/lib/
(C: 之前有/)。该文件夹包含以下内容:
但是当我运行时
System.out.println(this.getClass().getResource("").getPath());
我得到以下输出:
file:/C:/Users/MYPC/Documents/Processing/tools/GitManager/tool/GitManager.jar!/git_manager/tool/
这个jar文件的内容是:
这是我使用的代码。我使用了 3 种不同的方法(其中一种出现在 Processing Tool Template 存储库的自述文件中),尽管它们本质上都做同样的事情。同样,最终目标是将图标加载到按钮上。
// some other function that executes during runtime
ImageIcon init = createImageIcon("gitinit.png", "git init Icon");
System.out.println("-------------------------------------");
loadImage("gitinit.png");
b.setIcon(new ImageIcon(("src\\gitinit.png")));
System.out.println(b.getIcon());
public Image loadImage(String theFilename) {
if (theFilename.startsWith(File.separator)) {
return new ImageIcon(theFilename).getImage();
} else {
URL img;
try{
img = this.getClass().getResource(getPath(theFilename));
return new ImageIcon(img).getImage();
}
catch (NullPointerException n)
{
//System.out.println("Null pointer Exception");
n.printStackTrace();
return null;
}
}
}
protected ImageIcon createImageIcon(String path, String description) {
java.net.URL imgURL;
try{
//imgURL = GitOptionToolbar.class.getResource(path);
imgURL = GitOptionToolbar.class.getClass().getResource(path);
}
catch(NullPointerException n)
{
imgURL = null;
System.out.println("null");
}
if (imgURL != null) {
System.out.println("Found " + path);
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
public String getPath(String theFilename) {
if (theFilename.startsWith("/")) {
return theFilename;
}
return File.separator + "data" + File.separator + theFilename;
}
所以,我认为要做的是以某种方式将当前路径上移 3 个级别,然后使用相对的“data/gitinit.png”或“data/tools/xyz.png”,但我该怎么做?
还有,这个假设正确吗?
我知道这个问题真的很长,很抱歉,我只是想提出到目前为止我所有的实验。此外,我知道很多事情都是随机的,特别是尝试文件夹名、/、\和文件名的不同组合,并将 gitinit.png 放在每个可能的文件夹中,我也为此道歉。只是我想在在这里发布之前尝试一切可以的东西:)
谢谢!
最佳答案
您需要使用
getResource("/data/toolbar/logos/gitnit.png")
从数据
一直到图像的完整路径。我不习惯使用 Eclispe,也不习惯将“data”目录置于 src
的同一级别。在 Netbeans 中,我将它放在 src
中,但看起来 Eclipse 会为您处理这些问题,查看您的图像。
关于java - 无法使用 getResource() 将图像添加到按钮(使用 ant 获取 NullPointerException- 构建项目),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22361198/