2

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)

enter image description here

I've tried:

getResource("") 
getResource(".") 
getResource("./") 
getResource("/img/logo.png") 
Bootstrapper.class.getProtectionDomain().getCodeSource().getLocation().getPath()
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Reinard
  • 3,624
  • 10
  • 43
  • 61

3 Answers3

5
this.getClass().getResource("/net/sharpcode/crawler/img/logo.png")
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
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");
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

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")
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674