Java: Referencing an image within a package
Hello everyone. I am running into a small bit of difficulty with images I want to use in a Java program, keeping them bundled with the program in a JAR file and accessing them within the package.
For those who are thinking it, this is definitely not homework. In my program, I have several images I would like to use on buttons on a toolbar. I am under the impression Code:
JButton button = new JButton(new ImageIcon("icon.png")); I have Googled, and I found something that comes close, but it deals with fetching images from a URL - nothing that deals with local files, more specifically, local images kept inside of a JARchive. Any help would be greatly appreciated. :) |
Hi -
I think the word "URL" might be misleading here. A URL *can* be a local file (as well as a remote web link), and I think it's probably exactly what you want: http://forums.sun.com/thread.jspa?threadID=5347567 Code:
import java.awt.BorderLayout; |
use
Code:
new ImageIcon(getClass().getResource("myimage.png")); |
mrcheeks -
You're correct, but I wanted to reassure indienick that the "read java.net.URL" approach was also correct (and, in fact, the one Sun shows in the on-line Java docs). |
All times are GMT -5. The time now is 04:35 AM. |