Search code examples
javaswingjbuttonembedded-resourceimageicon

Regarding a JButton and an ImageIcon


I am currently reading a book on java, and I am currently studying the swing graphical user interface components. While I was doing so, I stumbled upon a code example, where the author was setting an image on a JButton with a very unusual way, depicted below:

Icon bug1 = new ImageIcon( getClass().getResource( "bug1.gif" ) );

In order for the above to work, you need to have the image on the same folder as the .class files. Can someone explain to me why is he using this particular code (which as far as I know, it must be reflection code, but then again, I am not particularly sure about this one) and if there is one way for me to do the same thing, without getting things as complicated as he does?


Solution

  • Things are complicated only if you don't understand them. Once you have understood what the above code does, it will be extremely simple.

    getClass() returns the Class object of the current object (this). getResource() called with a relative path as above, looks for a file, in the classpath, named bug1.gif, and in the same package as the Class object being called. So it looks for bug1.gif in the same package as the class containing the above code. getResource() returns a URL. And the ImageIcon constructor takes a URL as argument, loads the image bytes from this URL, and constructs an ImageIcon from these bytes.

    So the whole thing just creates an ImageIcon from a file available from the classpath, in the same package as the class calling this code. And this makes sense: you put the images used by a given class in the same package as the class, and you release a jar containing the classes and the images of the application.

    You would have figured all this by yourself by reading the javadoc of all these methods.