|
|
||
|
In this tutorial I create a real-world example that loads resources (e.g. properties and images) from a jar to make the app Java Web Start ready.
Here is a first impression of the Hello Venus resource loading example. The icons are
retrieved from the jar as well as menu.properties
which is used
to create the help menu.
Retrieving resources from jars isn't hard if you use the resource anchor trick presented here.
Start with creating an empty class and package it with your resources. Example:
public class ResourceAnchor { public ResourceAnchor() { } }
The ResourceAnchor
class is just here to identify the Java archive
that holds your resources.
There is no need to burn the weather report on your toast in the constructor.
Here is the content of tutorial.jar
that holds ResourceAnchor.class
and all
resources we want to retrieve:
vamp/tutorial/CmdShowUrl.class vamp/tutorial/HelloVenus$1.class vamp/tutorial/HelloVenus.class vamp/tutorial/Main.class vamp/tutorial/menu.properties vamp/tutorial/ResourceAnchor.class vamp/tutorial/WebBrowser.class vamp/tutorial/images/inform.gif vamp/tutorial/images/world2.gif
To retrieve your resources you need to get a hand on a class loader. Here's the pick-up line:
ClassLoader cl = ResourceAnchor.class.getClassLoader();
Now, you are ready to drill for bits. Here is how you get an icon from tutorial.jar
:
URL worldIconUrl = cl.getResource( "vamp/tutorial/images/world2.gif" ); ImageIcon worldIcon = new ImageIcon( worldIconUrl );
Or in compressed form:
ImageIcon worldIcon = new ImageIcon( cl.getResource( "vamp/tutorial/images/world2.gif" ) );
Tip: Use only lower case resource names as on some machines retrieving resources with
both upper and lower case letters will fail (e.g rename World2.gif to world2.gif ).
|
And here is how to get menu.properties
from tutorial.jar
:
Properties props = new Properties(); try { props.load( cl.getResourceAsStream( "vamp/tutorial/menu.properties" )); } catch( IOException ioex ) { System.err.println( "*** failed to load properties: " + ioex.toString() ); }
That's it. That's all there is to it.
|
Send your comments, suggestions, praise or poems to webmistress@vamphq.com | Copyright © 2001, 2002 Gerald Bauer |