I can't seem to get access to images in my application when i pack the executable jar file. I've tried everything i can find in examples and nothing is working.

Can anyone help please?

Is there a way of specifying where images are in the manifest file.

Read image location with java.net.URL

URL urlImage = getClass().getResource("Image/button.gif");
Image img = Toolkit.getDefaultToolkit().getImage(urlImage);

"Image" folder is on same level(in same directory) as your java file from where you call this image

Thanks for the reply but i can't get it to work. When i use this i can run it through the IDE but when i try to run the jar the application won't even load. I've made sure that the manifest has the main class.

Ok i've got it working now.

Thanks for your help.

Hi ,
I m also facing the same problem ..u said u have got it working...Please tell how?

I just created the getImage method and called it to place the image. With the code below you would have packed the jar with a folder containing 'myimage'. This code should work from a Jar.

import java.awt.*;
import javax.swing.*;
import java.net.URL;

public class JarImage
{
    public JarImage()
    {
        JFrame frame = new JFrame();
        JButton button = new JButton
            (new ImageIcon(getImage("images/myimage.gif")));
        frame.getContentPane().add(button, BorderLayout.SOUTH);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 500);
        frame.setLocation(300, 100);
        frame.setVisible(true);
    }
    
    private Image getImage(String pathName)
     {
         URL url = getClass().getResource(pathName); 
        Image image = Toolkit.getDefaultToolkit().getImage(url);
        return image;    
     }
    
    public static void main(String[] args)
    {
        JarImage jar = new JarImage();
    }
}
URL urlImage = getClass().getResource("Image/button.gif");
Image img = Toolkit.getDefaultToolkit().getImage(urlImage);
public JarImage()
    {
        JFrame frame = new JFrame();
        JButton button = new JButton
            (new ImageIcon(getImage("images/myimage.gif")));
        
    }
    
    private Image getImage(String pathName)
     {
         URL url = getClass().getResource(pathName); 
        Image image = Toolkit.getDefaultToolkit().getImage(url);
        return image;    
     }

Cerberus reused the peace of code that I give it to him and displayed image as icon on button, but there are many others ways how to display image and doesn't have to be button. Choice are yours

This article has been dead for over six months. Start a new discussion instead.