Java Path ImageIcon URL .JAR

强颜欢笑 提交于 2019-11-28 01:33:18

If you have the following package layout

+---src
    |   img0.png
    \---fichierPointJava
        |       img1.png
        |       <YourClass.java>

then the the following should work

// using the classloader in instance context
getClass().getClassLoader().getResource("img0.png");
getClass().getClassLoader().getResource("fichierPointJava/img1.png");

// using the classloader in class/static context
<YourClass>.class.getClassLoader().getResource("img0.png");
<YourClass>.class.getClassLoader().getResource("fichierPointJava/img1.png");

// using the class in instance context
getClass().getResource("../img0.png");
getClass().getResource("/img0.png");
getClass().getResource("img1.png");
getClass().getResource("/fichierPointJava/img1.png");

// using the class in static/class context
<YourClass>.class.getResource("../img0.png");
<YourClass>.class.getResource("/img0.png");
<YourClass>.class.getResource("img1.png");
<YourClass>.class.getResource("/fichierPointJava/img1.png");

When using the ClassLoader you need to pass the full qualified name of the resource, i.e including the package name.

When using the Class then the path - if not starting with / - is relative to the package where the class which is trying to load the resource is located, otherwise it is the absolute name of the resource.

You can read more about ClassLoader#getResource and Class#getResource in the javadocs.

Make sure that the ant target you are running to create the jar include the *.png resources. You can verify this by opening the jar with the zip-tool of your choice. The directory src should not be included.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!