Creating an Executable .jar File

Finally, when you're ready to pass out your game to friends, the last thing you want is to give them arcane instructions on how to run the code. Telling another programmer to type something like this at the command line might be okay:

java com.brackeen.javagamebook.tilegame.GameManager

But the casual user might not even know what a command line is or even what to do if problems occur. It's probably a good idea to make it easier by creating an executable .jar file. With an executable .jar file, all the user has to do is double-click the .jar file, and the game starts right up. Your programmer friends would probably appreciate the time it saves them as well. If you're unfamiliar with what a .jar file is, it's a Java archive file-basically just a container for a group of classes. All the classes for your game are stored in the .jar file, which is usually compressed. To make the .jar file executable, you specify which class to run in the .jar's manifest file. The manifest file is called META-INF/MANIFEST.MF inside the .jar. For this platform game, the manifest file looks something like this:

Manifest-Version: 1.0
Main-Class: com.brackeen.javagamebook.tilegame.GameManager

When you double-click a .jar file, the Java VM starts up and looks at the .jar file's manifest. If the Main-Class attribute is found, it runs the specified class. If there is no manifest or the Main-Class attribute doesn't exist, the VM just pretends that nothing happened and exits. If you're using the jar tool to create .jar files, first create a manifest file in a text editor and then use the -m option to add the manifest file to your .jar. If you're using Ant to build .jar files, Ant can create the manifest file automatically and add it to the .jar. shows a sample Ant target that creates an executable .jar file for the game.

Listing 5.15 Sample Ant Build Target for Making an Executable .jar

<target depends="compile">
 <jar jarfile="${basedir}/tilegame.jar">
 <manifest>
 <attribute name="main-class"
 value="com.brackeen.javagamebook.tilegame.GameManager"/>
 </manifest>
 <fileset dir="${destdir}" includes="**/*.class"/>
 </jar>
</target>

Manifests can also contain all sorts of other data. Check out the "Jar Guide" in the Java SDK documentation for all the information, and see for more information on Ant. Note, however, that not everyone will be able to execute a .jar by double-clicking on it. Linux users won't be able to, and someone on a Windows machine might have WinZip set up to open .jar files instead of the Java runtime. If you can't double-click the .jar, run this command at the console:

java -jar tilegame.jar

Also check out , "Game Design and the Last 10%," for information on other ways to deploy your game, such as using Java Web Start.