Creating an Executable JAR in Java

While not quite as hassle-free as a native executable, an executable JAR file makes it possible to run a java program by double-clicking its icon–at least as long as the operating system’s file associations are set up right.

1. If you have not already done so, download and install the Java Development kit. Details are given in a previous tutorial.

2. In any convenient location, create a new directory named “ExecutableJARTest”.

3. Copy the files JavaPathAndProgramNameSet.bat and ProgramBuild.bat (created in a previous tutorial) to the newly created ExecutableJARTest directory.

4. Still in the ExecutableJARTest directory, create a new text file named “ExecutableJARTest.java” , containing the following text.

import javax.swing.*;

public class ExecutableJARTest
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame();
        frame.pack();
        frame.setVisible(true);
        frame.setSize(256, 64);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(new JLabel("This is an executable JAR"));
    }
}

5. Double-click the icon for ProgramBuild.bat to run it.  A console window will appear, and ExecutableJARTest.java will be compiled to a class file.

6. Still in the ExecutableJARTest directory, create a new text file named “ProgramJarify.bat”, containing the following text.

call JavaPathAndProgramNameSet.bat

dir /b *.class >_ClassFileNames.txt
echo Main-Class: %programName%>%programName%.mf
%javaPath%\jar.exe cvfm %programName%.jar %programName%.mf @"_ClassFileNames.txt"

pause

7. Double-click the icon of ProgramJarify.bat to run it.  A console window will appear, and a new file called ExecutableJARTest.jar will be created (along with several supporting files).

8. Double-click the icon of the newly created ExecutableJARTest.jar file.  A Java frame will appear, containing the text “This is an executable JAR”.

Notes

  • From the operating system’s perspective, executable JARS aren’t technically executable.  Rather, double-clicking them causes them to be “opened” with java.exe.
  • The Java Swing UI framework is used in this example because double-clicking an executable JAR that performs only console operations doesn’t currently cause anything to happen.  However, the jar can be “executed” from the command line or a batch file by entering “java.exe -jar [name of the program].jar”.
This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s