Jar get image as resource

﹥>﹥吖頭↗ 提交于 2019-12-29 01:50:10

问题


I'm trying to get load an image from my jar. But no matter what string I supply for getResource() it always returns null.

try {
    System.out.println(Bootstrapper.class.getResource("./img/logo.png").toURI().getPath());
} catch (URISyntaxException ex) {
    Logger.getLogger(CrawlerFrame.class.getName()).log(Level.SEVERE, null, ex);


   }
   ImageIcon ii = new ImageIcon(Bootstrapper.class.getResource("./img/logo.png"));
   setIconImage(ii.getImage());

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at net.sharpcode.crawler.ui.CrawlerFrame.init(CrawlerFrame.java:35) at net.sharpcode.crawler.ui.CrawlerFrame.(CrawlerFrame.java:28) at net.sharpcode.crawler.Bootstrapper$1.run(Bootstrapper.java:55)

I've tried:

getResource("") 
getResource(".") 
getResource("./") 
getResource("/img/logo.png") 
Bootstrapper.class.getProtectionDomain().getCodeSource().getLocation().getPath()

回答1:


this.getClass().getResource("/net/sharpcode/crawler/img/logo.png")



回答2:


Get rid of the "./" part - just use:

Bootstrapper.class.getResource("img/logo.png");

... that's if it's relative to Bootstrapper.class. If the img "directory" is in the root of the jar file, use

Bootstrapper.class.getResource("/img/logo.png");



回答3:


From the stack trace I see the Bootstrapper class lies in net.sharpcode.crawler package. It means the following path ./img/logo.png will be resolved to /net/sharpcode/crawler/img/logo.png. I guess /img is a top level directory, so either use absolute path:

Bootstrapper.class.getResource("/img/logo.png")

or load via ClassLoader:

Bootstrapper.class.getClassLoader().getResource("img/logo.png")


来源:https://stackoverflow.com/questions/10163012/jar-get-image-as-resource

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