In this tutorial, we will show you how to create a executable JAR – When you double click on it, it runs the defined main class in manifest file.

1. AWT Example

Create a simple AWT Java application, just display label and print out some funny characters ~

AwtExample.java
package com.mkyong.awt;
 
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
 
public class AwtExample {
 
	public static void main(String[] args) {
 
		Frame f = new Frame();
		f.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		f.add(new Label("This JAR file is executable!"));
		f.setSize(500, 500);
		f.setVisible(true);
	}
}

2. Manifest.txt

Create a manifest.txt file.

Manifest.txt
Main-Class: com.mkyong.awt.AwtExample

Uses Main-Class as the entry point of this Jar file, when you double click on this Jar file, the “AwtExample.class” main() method will be launched.

Note
Be sure that your manifest file ends with a new line, else your manifest file will not be parsed and failed to generate the manifest.mf. Read this http://docs.oracle.com/javase/1.4.2/docs/tooldocs/windows/jar.html

Read this jar reference guide :
Be sure that any pre-existing manifest file that you use ends with a new line. The last line of a manifest file will not be parsed if it doesn’t end with a new line character.

3. Jar file

Create a Jar file by adding “AwtExample.class” and “manifest.txt” files together.

Assume your project folder structure as follows :

c:\test\classes\com\mkyong\awt\AwtExample.class
c:\test\classes\manifest.txt

You can issue following command to create a “AwtExample.jar.

jar -cvfm AwtExample.jar manifest.txt com/mkyong/awt/*.class

Output

C:\test\classes>jar -cvfm AwtExample.jar manifest.txt com/mkyong/awt/*.class
added manifest
adding: com/mkyong/awt/AwtExample$1.class(in = 638) (out= 388)(deflated 39%)
adding: com/mkyong/awt/AwtExample.class(in = 880) (out= 541)(deflated 38%)

4. Demo

Now, the “AwtExample.jar” is executable, double clicks on it, see the output :

make-jar-executable

References

  1. http://docs.oracle.com/javase/1.4.2/docs/tooldocs/windows/jar.html
  2. http://www.mkyong.com/java/how-to-add-your-manifest-into-a-jar-file/
  3. http://www.mkyong.com/java/the-java-archive-tool-jar-examples/
Tags :
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

Related Posts

Popular Posts