Java Path ImageIcon URL .JAR

笑着哭i 提交于 2019-11-26 21:58:19

问题


I may have made of try, none works..

The file is:

/Users/Toto/Desktop/Titi/IUT/Java/TP2/project/src/fichierPointJava/img1.png

fichierPointJava is the name of the package .

I launch the ant when I am situated in project which contains the build.xml

Here are the codes that I tested:

URL urlImage1=this.getClass().getClassLoader.getResource("/src/fichierPointJava/img1.png");
URL urlImage1=this.getClass().getClassLoader.getResource("/fichierPointJava/img1.png");
URL urlImage1=this.getClass().getClassLoader.getResource("fichierPointJava/img1.png");
URL urlImage1=this.getClass().getClassLoader.getResource("/img1.png");
URL urlImage1=this.getClass().getClassLoader.getResource("img1.png");

System.out.println("Value = "+ urlImage1);

I made out a will with or without this, and with or without getClassLoader()

Hope someone will help me.

Thanks you


回答1:


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.



来源:https://stackoverflow.com/questions/16924347/java-path-imageicon-url-jar

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