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.favtuts.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);
	}
}

To compile the Java file

$ javac AwtExample.java
$ ls
'AwtExample$1.class'   AwtExample.class   AwtExample.java

2. Manifest.txt

Create a manifest.txt file.

Manifest.txt

Main-Class: com.favtuts.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\favtuts\awt\AwtExample.class
c:\test\classes\manifest.txt

.
├── AwtExample.java
└── classes
    ├── com
    │   └── favtuts
    │       └── awt
    │           ├── AwtExample$1.class
    │           └── AwtExample.class
    └── manifest.txt

4 directories, 4 files

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

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

Output

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

4. Demo

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

References

  1. http://docs.oracle.com/javase/1.4.2/docs/tooldocs/windows/jar.html
  2. How to add a manifest into a Jar file
  3. The Java Archive Tool (JAR) Examples
  4. Java – Read a file from resources folder

Leave a Reply

Your email address will not be published. Required fields are marked *