Bugster
Bugster

Reputation: 1594

java.lang.NullPointerException when setting icon?

I've recently tried to set my default application icon with a .ico file I made myself. This is the code I used to create the icon:

initComponents();
java.net.URL url = ClassLoader.getSystemResource("/src/calculatormedii/resources/CMedii.ico");
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.createImage(url);
getFrame().setIconImage(img);

I have no idea why it's so difficult to set the java desktop application icon in netbeans, it should just be a property field like the rest. When I try to run the program, these errors show up:

    Uncaught error fetching image:
java.lang.NullPointerException
    at sun.awt.image.URLImageSource.getConnection(URLImageSource.java:99)
    at sun.awt.image.URLImageSource.getDecoder(URLImageSource.java:113)
    at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:240)
    at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:172)
    at sun.awt.image.ImageFetcher.run(ImageFetcher.java:136)

No idea what to do now. If there is an alternate way to set the application icon please specify it (Like a property field in netbeans or something)

Upvotes: 1

Views: 2272

Answers (2)

Snicolas
Snicolas

Reputation: 38168

You shall print more of your stack trace. If you look further down, you will find the caller line inside your code that leads to the exception in java librairies.

But in your case, the problem comes from the fact that the path you give to getSystemResource as a parameter should be relative to the folder containing the actual class file of the class you are coding in.

More precisely, you can use both :

  • ClassLoader.getSystemResource and then the path has to be relative to your classpath entries
  • getClass.getResourceUrl and the the path has to be relative to the class file of class you are coding in.
  • X.class.getResourceUrl and the the path has to be relative to the class file of class X.

If you use eclipse with maven, a default folder structure is to have

 /src/main/java
 /src/main/resources

And then everything is handled for you : copying the resources files inside the same folder as the java files are compiled to.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500665

I strongly suspect it's the URL you're using. Using ClassLoader.getSystemResource, you shouldn't need a leading slash - but I very much doubt that you want the src part either. You should make sure that your icon is copied to the same place that your class files is (e.g. a bin directory) and then just use:

URL url = ClassLoader.getSystemResource("calculatormedii/resources/CMedii.ico");

Upvotes: 4

Related Questions