0

Picture inside .jar file wont work when I export it.

I made a Java program that displays a picture, and it works perfectly in Eclipse, but when I export it to a .jar file, it wont display the picture. I just started learning Java, and I have no experience with creating Jar files and using files from inside the jar file.

Heres my code:

import javax.swing.*;
class displayPicture{
public static void main(String args[]){


    JFrame frame = new JFrame();
    ImageIcon icon = new ImageIcon("src/img.gif");
    JLabel label = new JLabel(icon);

    //Create the frame
    frame.add(label);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

}
}

It shows the picture when I run it in Eclipse, but when I export it to a .jar file, it just shows a blank window.

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
hhaslam11
  • 191
  • 2
  • 7
  • 24
  • possible duplicate of [Exported JAR Won't Read Image](http://stackoverflow.com/questions/15992609/exported-jar-wont-read-image) – nrubin29 Mar 18 '14 at 01:50

1 Answers1

3

Two things...

First

The path src is unlikely to exist once the code is build

Second

ImageIcon(String) assumes the String reference is a reference to a file on the file system. Resources stored within the context of the application are not files and are treated differently. They are commonly known as embedded resources.

Instead, try using ImageIcon icon = new ImageIcon(displayPicture.class.getResource("img.gif")); or ImageIcon icon = new ImageIcon(displayPicture.class.getResource("/img.gif"));

I prefer to use ImageIO.read as it throws an IOException when something goes wrong and supports more file formats.

See Reading/Loading an Image for more details.

You should also take the time to have a read through Code Conventions for the Java Programming Language and Initial Threads

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • It gives me and error: displayPicture cannot be resolved to a type. Am I missing something here? – hhaslam11 Mar 18 '14 at 02:01
  • The example is based on your example `displayPicture` is the name of your class. Because you can't use `getClass()` from a `static` context, I had to use the name of the class instead. Based on the example you provided, the solution in the answer is correct. You are using it a different context beyond the scope of the available information I have... – MadProgrammer Mar 18 '14 at 02:05