getClass().getResource() 总是返回 null
我正在尝试设置位于 src 文件夹中的资源文件夹中的图像的 URL。它始终将 URL 设置为 null。图像就在那里,一切都被正确命名。有什么问题吗?谢谢!
我的文件结构:
- sp1
- 源代码
- 资源
- 01.png
- 资源
- 源代码
这是我的代码,我试图在其中设置图片的 URL:
this.setImagePath(getClass().getResource("/resources/01.png"));
并且 setImagePath 正在执行此操作,我确信这不是问题,因为我遵循执行并将其设置为相等为空。
public final void setImagePath(URL imagePath) {
this.imagePath = imagePath;
}
解决方案
我必须清理构建并重建。修复后它起作用了。
I am trying to set the URL of an image that is located in my resource folder in my src folder. It is always setting the URL to null. The image is there and everything is named correctly. What is the issue? Thanks!
My file structure:
- sp1
- src
- resources
- 01.png
- resources
- src
Here is my code where I am trying to set the URL for the picture:
this.setImagePath(getClass().getResource("/resources/01.png"));
And the setImagePath is doing this, I am sure this is not the problem, because I followed the execution and it is setting it equal to null.
public final void setImagePath(URL imagePath) {
this.imagePath = imagePath;
}
Solution
I had to clean the build and rebuild. It worked after that fix.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我必须清理构建然后重建。现在可以工作了。
I had to clean the build and then rebuild. Works now.
您需要检查,无论您如何构建,图像文件都会被复制到类文件编译到的位置。即,如果您的类是
com.foo.MyImageLoader
且位于/com/foo/MyImageLoader.class
,则图像应位于/resources/01.png
以便您能够像这样加载它。You need to check that, however you're building, the image file gets copied over to wherever the class files are compiled to. I.e. if your class is
com.foo.MyImageLoader
and located at<build dir>/com/foo/MyImageLoader.class
, then the image should be at<build dir>/resources/01.png
for you to be able to load it like that.没有生成jar的原因是pom.xml中的以下配置引起的,删除它并重新运行安装即可。
The cause of no jar generated is caused by following config in pom.xml, remove it and rerun install would be fine.
如果使用 JDeveloper,请确保您已选择要复制到类文件夹以供使用的文件的扩展名。右键单击该项目并选择项目属性以进入此屏幕。
If using JDeveloper, make sure that you have the extension of the file that you want copied to the classes folder for use selected. Right click on the project and choose project properties to get to this screen.
我猜 URL 应该是“01.png”而不是“/resources/01.png”
I would guess the URL should be "01.png" not "/resources/01.png"