Monday, December 22, 2008

How to create a executable Jar

Some Java applications are distributed as Jar files, where the user can just double-click the file and 'Bang!' the application opens up. When you double click on a normal Jar file we just get a error message saying "Failed to load Main-Class...".
 
Follow the following steps to create an executable Jar:
 
- Create a simple Swing program which displays a label
 
  1. import javax.swing.*;  
  2. import javax.swing.event.*;  
  3.   
  4. public class HelloWorldSwing {  
  5.     /** 
  6.      * Create the GUI and show it.  For thread safety, 
  7.      * this method should be invoked from the 
  8.      * event-dispatching thread. 
  9.      */  
  10.     private static void createAndShowGUI() {  
  11.         //Make sure we have nice window decorations.  
  12.         JFrame.setDefaultLookAndFeelDecorated(true);  
  13.   
  14.         //Create and set up the window.  
  15.         JFrame frame = new JFrame("HelloWorldSwing");  
  16.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  17.         //Add the ubiquitous "Hello World" label.  
  18.         JLabel label = new JLabel("Hello World");  
  19.         frame.getContentPane().add(label);  
  20.   
  21.         //Display the window.  
  22.         frame.pack();  
  23.         frame.setVisible(true);  
  24.     }  
  25.   
  26.     public static void main(String[] args) {  
  27.         //Schedule a job for the event-dispatching thread:  
  28.         //creating and showing this application's GUI.  
  29.         javax.swing.SwingUtilities.invokeLater(new Runnable() {  
  30.             public void run() {  
  31.                 createAndShowGUI();  
  32.             }  
  33.         });  
  34.     }  
  35. }  
 
- Compile and run it and ensure that it works properly
- Create a file called "mainClass" with the following content in the same directory where you have the class file - if you have put the class inside a package create the file at the root of the package
    Main-Class: HelloWorldSwing
 
    Note the empty new line after the class name.
- From the directory run the following command from the command prompt to create a Jar file - "jar cmf mainClass HelloWorldSwing.jar *.class". This creates the executable Jar file. Here "m" refers to the manifest file - "mainClass"
- Now double click on the Jar file and see your swing application come to life!!

No comments: