7

Basically, I want to include my main JFrame's icon in the JAR file, so not to need to load it from an external location.

To achieve this, I searched about Java's resource system. What I have done with Eclipse:

  1. I have created a new folder named "res":

  2. I have copied the files inside it using Windows' explorer:

  3. I have made that folder a source folder:

  4. I have written this code:

    URL url = ClassLoader.getSystemResource("/res/icona20.ico");
    

But url is null. What did I do wrong?

spongebob
  • 8,370
  • 15
  • 50
  • 83
  • 1
    Get rid of the `/res` in the path – Paul Samsotha Aug 31 '15 at 14:44
  • 1
    When you add a folder to the build path, it is not part of the path, instead all the contents are put at the root of the classpath – Paul Samsotha Aug 31 '15 at 14:51
  • 2
    See [here](http://stackoverflow.com/a/25636097/2587435) – Paul Samsotha Aug 31 '15 at 14:52
  • @peeskillet But I want the "src" folder to hold .java files only. I want resources to be in a separate folder. How could I achieve this? Am I going against the language recommendations? – spongebob Aug 31 '15 at 14:56
  • 1
    Look at the second example in the link. And no there is nothing wrong with put the files a different folder. If it's in the build path, all the files from the folder (excluding the folder) get built into the jar – Paul Samsotha Aug 31 '15 at 15:00

2 Answers2

5

As mentioned you seem to have added res as source folder, so it is a root, not to name, like src.

URL url = ClassLoader.getSystemResource("icona20.ico");

Class loaders use an absolute (case-sensitive) path, without explicit leading slash /....

Relative paths with an obligatory leading slash for absolute paths:

URL url = Xyz.class.getResource("/icona20.ico");

And you might prefer .png instead of .ico as the latter format is not standard in Java SE.

(About common practices.) The build tool maven uses as nice standard the following source folders:

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

Your usage of res is reminiscent of MS Visual Studio ;).

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • Yes, I have a [tag:vb.net] background. There's no static method like `ClassLoader.getResource(String)`. – spongebob Aug 31 '15 at 15:49
  • You are right; should have been `getSystemResource`. Corrected. I think Andres corrected too, and his answer then should be adequate & first. – Joop Eggen Aug 31 '15 at 16:01
  • As a side note, you cannot use .ico images for `JFrame`'s icons; you can use the .png format instead. Thanks for pointing out. – spongebob Sep 02 '15 at 11:31
3

The classloader will get the resources starting from each source folder you added to the classpath. Therefore, the URL should be the following:

URL url = ClassLoader.getSystemResource("icona20.ico");
spongebob
  • 8,370
  • 15
  • 50
  • 83
Andres
  • 10,561
  • 4
  • 45
  • 63