Adding Images To Jar File

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Adding images to Jar File


This is main class which Displays the Button with Image
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JavaHelp extends JFrame{
private ResourceClass resourceClass;
public JavaHelp() {
resourceClass = new ResourceClass();
setTitle("Image from jar");
setResizable(false);
getContentPane().setLayout(new BorderLayout());
Image img = resourceClass.loadIcon("Server.gif").getImage();
ImageIcon icon = new ImageIcon(img);
JButton button = new JButton(icon);
add(button);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e) {dispose();System.exit(0);}});
pack();
setVisible(true);
}
public static void main(String[] args) {
JavaHelp app = new JavaHelp();
}
}
This is utility class which give return the image object from jar file.

import java.awt.*;
import javax.swing.*;
public class ResourceClass {
public final static String FILESEPARATOR = System.getProperty("file.separator");
public ImageIcon loadIcon(String iconName) {
ImageIcon icon = null;
String sep;
try {
try {
icon = new ImageIcon(this.getClass().getResource("images" + FILESEPARATOR + iconName));
}
catch (Exception err) {
if (FILESEPARATOR.equals("/")) sep = "\\";
else sep = "/";
icon = new ImageIcon(this.getClass().getResource("images" + sep + iconName));
}
}
catch (Exception e) {
System.out.println("Couldn't load button icons\n" + e);
}
return icon;
}
}

To create the jar file following are the commands.


D:\Java\Mine\JarWork>jar cvfm JavaHelp.jar MANIFEST.MF *.class images\
added manifest
adding: JavaHelp$1.class(in = 507) (out= 351)(deflated 30%)
adding: JavaHelp.class(in = 1242) (out= 739)(deflated 40%)
adding: ResourceClass.class(in = 1447) (out= 788)(deflated 45%)
adding: VarUtils.class(in = 1437) (out= 790)(deflated 45%)
adding: images/(in = 0) (out= 0)(stored 0%)
adding: images/Thumbs.db(in = 16384) (out= 5291)(deflated 67%)
adding: images/Server.gif(in = 395) (out= 296)(deflated 25%)

Here images\ is a directory in which we have the image files.

You will get jar file which runs without having images in current directory.

You might also like