[an error occurred while processing this directive]
Domain for sale!
Start Search Contents Index Links About

Jar files and applets

Using Jar files

2003 - Week 20 - Havard Rast Blok

This year Remember Java has had quite a bad start, due to both personal on external issues. However, I have not given up on the project, and seek to keep on publishing tips and tricks. I hope you fellow programmers will continue to find it useful.

We usually make applications here at Remember Java. However, this week we will make an applet, and wrap it up in a JAR-file. This system is meant to be easy, but sometimes it is not. We will take one step at a time, and get it working for both applications and applets.

To have something to work with, start with a very simple program, a "Hello World!" for example. Make it runnable from the command prompt, and that's it.


HelloWorld.java

Now it is time to store the Hello World program in JAR-file, and make it runnable from within the archive. To do this, we need a so called manifest file which tells Java the main class of our very small application. Even if we are including only one class in the archive, we need the manifest file. The name of the manifest file does not matter, and for our purpose it need only one line that looks like this (assuming your main class file is called HelloWorld.class):

Main-Class: HelloWorld

Now, we would like to create a JAR archive containing the HelloWorld class file and the manifest file. Assuming we call the manifest file just mf, the command for creating a JAR file called hw.jar would be:

jar cmf mf hw.jar HelloWorld.class

Finally, our application may now be run from within the JAR file my using:

java -jar hw.jar


mf



hw.jar

We will now go back to the simple Hello World program, but this time as an applet. Again, it should be easy to make the class and html file necessary to make it run. No Jar-file is required at this point. The applet tag in the html file is, as you surly remember:

<applet code=HelloWorld.class width=100 height=100></applet>


HelloWorld.java


hw.html

Finally, we will add the applet to a JAR archive, as we did with the application. This time we do not need a manifest file, since it is already specified in the html-tag which class to load. This means that the creation of the JAR file is even easier:

jar cf hw.jar HelloWorld.class

And the addition to the applet tag only loads the hw.jar archive instead of a single class:

<applet code=HelloWorld.class archive="hw.jar" width=100 height=100></applet>


hw.jar



hw.html



site: Håvard Rast Blok
mail:
updated: 16 July 2010