O'Reilly logo

Swing Hacks by Chris Adamson, Joshua Marinacci

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

432
|
Chapter 11, Native Integration and Packaging
#85 Stuff Stuff in JARs
HACK
Packing Up
So far, this only proves that resource loading is a nice alternative to fully
specified paths. The next step is to put the application and its resources in a
JAR. You can do this with a single command:
jar cf buh.jar JarResourceLoading.class images sounds
Now, you run the application from the JAR by pointing the classpath into it.
Here’s what the output from that looks like:
[tonberry:] cadamson% java -classpath buh.jar JarResourceLoading
found image at jar:file:/Users/cadamson/Documents/O'Reilly/books/
swing%20hacks/HacksBook/PackagingInstalling/97/buh.jar!/images/
keagan-buh.jpeg
found sound at jar:file:/Users/cadamson/Documents/O'Reilly/books/
swing%20hacks/HacksBook/PackagingInstalling/97/buh.jar!/sounds/
buhbuhbuh.aiff
Note the different URLs: the image and sound are now found inside buh.jar.
The format of the
jar: URL is also interesting, in that it combines a regular
file:-type URL for the JAR file with a path inside that JAR, using a ! char-
acter to separate the two parts.
Double-Clicking JARs
There are a few more useful things you can do with JAR files. The first is
that you can eliminate the need to specify a main class on the command line
by specifying it in the JAR file instead. This has the advantage of making the
JAR a double-clickable application on graphical operating systems. To do
this, create a Manifest file with a line like the following in it:
Main-Class: JarResourceLoading
You put this into the JAR with the jar command’s m option. Because this
option requires an argument (as does
c, which creates the JAR file), you
specify the JAR file to be created and the Manifest file to be inserted in the
order that you use the
m and c options. So, you can create the JAR like this:
jar cfm buh.jar manifest.txt JarResourceLoading.class images sounds
or like this:
jar mcf manifest.txt buh.jar JarResourceLoading.class images sounds
You could also create the JAR with one command and add the Manifest
with another. In any case, you can run the application inside the JAR by
double-clicking its icon, or with the command:
java -jar buh.jar

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required