Professional Documents
Culture Documents
Adding Images To Jar File
Adding Images To Jar File
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;
}
}
You will get jar file which runs without having images in current directory.