22 Aug 2012

Problem of images in a jar file


I was creating a small application using Swing API  in which i had to use some images for various
labels. Then i had to bundle this application in a jar file. The created jar file should display all of the images on execution.


Code for creating a jar file
cmd>jar cmf manifest.txt gui.jar abc/GuiClinet.class images/dice.gif 

Structure of the application :

I created and bundled the application but things didn't turn out as expected. The jar file on execution was not displaying the images.

There is how i add images to labels


/*
                       ImageIcon img = new ImageIcon("images/dice.gif");  
                       JLabel imglab = new JLabel(img);  
                        panel.add(imglab);         
                        frame.add(panel);           
*/




Lets figure out what i was doing wrong and how i corrected it.

1. Use getResource() to get image reference.
Problem : on executing the jar file it was not showing the images.
Solution :The reason for problem was the jar file was not able to get the references of the images. Using the ImageIcon() to get the image reference is not a way to go when looking for image inside a jar file.
So i changed the code  to
/*
String path = "images/dice.gif";
URL  imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);

else {
System.err.println("Couldn't find file: " + path);
return null;
}
*/




2 Directory structure of images inside jar is important.
Problem : After i changed the code and create a new jar file , while creting the jar file i got the error                   Couldn't find fiel images/dice.gif
The reason for the problem i was giving the relative name "images/dice.gif" to the directory "abc" (which is a pacakge  to store .class file) .So the compiler was looking for image files in home_dir/myapp/images/*gif , but since images is not placed under abc directory  thats why i was getting the error
Solution :Placed the /images directory under /abc ,so compiler can now find images in home_dir/myapp/images/dice.gif.
now application structure look something like this





And issued new jar file creation command :
cmd>jar cmf  manifest.txt  gui.jar abc/GuiClient.class abc/images/dice.gif 



Now problem is solved and everybody is happy.

No comments:

Post a Comment