LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Java: Referencing an image within a package (https://www.linuxquestions.org/questions/programming-9/java-referencing-an-image-within-a-package-701066/)

indienick 01-30-2009 12:04 PM

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"));
is referencing the filesystem (the directory location where the JAR exists) but what I want is to be able to access the resource within the JAR. Further explanation: if the JAR I am running is located at /home/indienick/program.jar, the ImageIcon class is (probably) looking for the image at /home/indienick/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. :)

paulsm4 01-30-2009 01:07 PM

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;
import java.awt.Image;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
 
public class DisplayJarPNG
{
    public static void main(String[] args) throws MalformedURLException,
        IOException
    {
        URL url = new
            URL("jar:file:/C:/lib/images.jar!/sameDir/sameImage.png");
        Image image = ImageIO.read(url);
 
        // Use a label to display the image in a frame
        JFrame frame = new JFrame();
        JLabel label = new JLabel(new ImageIcon(image));
        frame.getContentPane().add(label, BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
        frame. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

'Hope that helps .. PSM

mrcheeks 02-01-2009 07:15 PM

use
Code:

new ImageIcon(getClass().getResource("myimage.png"));

paulsm4 02-01-2009 10:02 PM

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.