设置没有完整路径的imageIcon

时间:2016-12-31 15:48:50

标签: java image swing jlabel embedded-resource

我试图在Jlabel上显示图标,但我得到了#34; NullPointerException"每次我运行它。它确实在我完成整个路径时运行,但我不想这样做因为我想在环境中移动java程序。

jLabel1.setIcon(new ImageIcon(this.getClass().getResource("/data/images/image.jpg")));

我认为问题出在我试图使用的道路上。

我粗糙的项目环境是:

projectfolder/src
projectfolder/data/images/image.jpg

我尝试过使用:

/image.jpg
/data/images/image.jpg
data/images/image.jpg
.\\data\\images\\image.jpg

我做错了什么?

1 个答案:

答案 0 :(得分:0)

Class#getResource()返回相对于您班级位置的资源。请改用ClassLoader#getResource()。如果使用默认的类加载器,它将返回相对于程序的类路径的资源。

this.getClass().getClassLoader().getResource("data/images/image.jpg")

您应该将数据文件夹放在src文件夹中。否则,数据文件夹不包含在程序的.jar