Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does getClass().getResource(...) do when creating ImageIcon?

Tags:

java

swing

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)?

like image 265
Tomáš Zato - Reinstate Monica Avatar asked Jun 13 '26 17:06

Tomáš Zato - Reinstate Monica


2 Answers

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-

like image 56
Tripp Kinetics Avatar answered Jun 15 '26 05:06

Tripp Kinetics


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.

like image 32
A4L Avatar answered Jun 15 '26 06:06

A4L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!