3

I wanted to create a pretty button in my GUI. There is a tutorial describing how to make all kinds of pretty buttons.
The thing is, they use ImageIcon. So next step was looking up how image icons work and what they do. There is another tutorial on the same site titled "How to use icons".
It provides you with this code:

/** Returns an ImageIcon, or null if the path was invalid. */
protected ImageIcon createImageIcon(String path,
                                           String description) {
    java.net.URL imgURL = getClass().getResource(path);
    if (imgURL != null) {
        return new ImageIcon(imgURL, description);
    } else {
        System.err.println("Couldn't find file: " + path);
        return null;
    }
}

The line java.net.URL imgURL = getClass().getResource(path) is very confusing to me. Why won't they do directly return new ImageIcon(path, description)?

Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
  • 1
    It might help you. Check it [here](http://stackoverflow.com/questions/23478984/read-image-from-another-directory?answertab=votes#tab-top) or [here](http://stackoverflow.com/questions/23506089/how-to-add-txt-file-to-a-jtextarea-and-where-to-place-my-txt-file/23506266#23506266) – Braj Jun 04 '14 at 20:27
  • Basically, getRescource uses the class's ClassLoader to try and find a reference to the named resource within the class-path context of the ClassLoader. Depending on how is used, this can use a relative path (to the class) or a absolute path (relative to each class-path entry) – MadProgrammer Jun 04 '14 at 21:34

3 Answers3

3

getResource() searches the entire path available to the ClassLoader responsible for loading that class, searching for that resource. Including things like searching inside JAR files on the classpath, etc.

http://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getResource-java.lang.String-

Tripp Kinetics
  • 5,178
  • 2
  • 23
  • 37
1
getClass().getResource(path)

locates the icon on the classpath and gives back the URL to use to load it. This is different from what you suggest to use. The constructor that takes only String loads the icon from the filesystem. It is done via getClass().getResource(path) so that you can package your icon and all resources your application needs within your distribution jar and still find and load it. Otherwise you'd have to rely on some path on the filesystem and make sure they exist where you expect them so that you can work with relative paths.

Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
A4L
  • 17,353
  • 6
  • 49
  • 70
-1

The getClass().getResource(path) loads the resource in relation to where the class file sits. This will work from an IDE as well as after the class has been packaged into a JAR file

Dawnkeeper
  • 2,844
  • 1
  • 25
  • 41