Saturday 23 July 2011

How to create Executable jar for an Applet


Creating an executable jar file for an applet

      To create an executable a jar file there should be a main class (a class with a main method) inside the jar to run the software. An applet has no main method since it is usually designed to work inside a web browser. To make the jar file executable I had to do two things:


First, I created a new class inside the jar file as a main class which I called StartClass. The job of this class is to call and host the applet; hence if the jar file is executed, the applet method is invoked. Check out the following code that I used supported by few comments to explain what it does.


package CaesarCodePackage;
 public class StartClass {

     public static void main(String [] args)
      {
         // create an object of type CaesarCode which is

         //the main applet class
         CaesarCode theApplet = new CaesarCode();
         theApplet.init();   // invoke the applet's init() method
         theApplet.start();  // starts the applet

         // Create a window (JFrame) and make applet

         //the content pane.
          javax.swing.JFrame window = new javax.swing.JFrame

          ("Caesar's Cipher");
          window.setContentPane(theApplet);
          window.setDefaultCloseOperation

          (javax.swing.JFrame.EXIT_ON_CLOSE);
          window.pack();              // Arrange the components.
          window.setVisible(true);    // Make the window visible.
        }

}

Second, I had to edit the MANIFEST.MF file and add the following line to define my main class correctly

Main-Class: CaesarCodePackage.StartClass

please note that ‘CaesarCodePackage’ is my package’s name and ‘StartClass’ is the name of my main class (the one with the main method that I used to call the applet). If this step is not performed correctly the following error is more likely to occur if you try to execute the jar file:
Failed to load Main-Class manifest attribute
A final note would be that, to successfully execute jar files on your system, you need to have JRE installed and the Jar files must be associated with javax.exe (javax.exe is located inside the bin directory of your JRE folder e.g. C:\Program Files\Java\jre6\bin)

No comments:

Post a Comment