Making an executable JAR from the command line

suggest change

To make a jar, you need one or more class files. This should have a main method if it is to be run by a double click.

For this example, we will use:

import javax.swing.*;
import java.awt.Container;

public class HelloWorld {

    public static void main(String[] args) {
        JFrame f = new JFrame("Hello, World"); 
        JLabel label = new JLabel("Hello, World");
        Container cont = f.getContentPane();
        cont.add(label);
        f.setSize(400,100); 
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}

It has been named HelloWorld.java.

Next, we want to compile this program.

You may use any program you want to do this. To run from the command line, see the documentation on compiling and running your first java program.

Once you have HelloWorld.class, make a new folder and call it whatever you want.

Make another file called manifest.txt and paste into it

Main-Class: HelloWorld

End the manifest file with a newline, or jar may ignore the last line. A Class-Path entry names other libraries. The original example also listed HelloWorld.jar itself, which does not add this JAR’s own classes.

Put it in the same folder with HelloWorld.class

Use the command line to make your current directory (cd C:\Your\Folder\Path\Here on Windows) your folder.

Use Terminal and change directory to the directory (cd /Users/user/Documents/Java/jarfolder on Mac) your folder

When that is done, type in jar -cvfm HelloWorld.jar manifest.txt HelloWorld.class and press enter. This makes a JAR file (in the folder with your manifest and HelloWorld.class) using the class files specified and named HelloWorld.jar. In -cvfm, c creates the archive, v is verbose, f names the JAR file, and m reads the manifest. The f and m arguments must stay in that same order.

After these steps, go to your directory with the manifest file and you should find HelloWorld.jar

Clicking on it should display Hello, World on a label.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents