Using resources from inside .jar package.

When we pack all our java classes, libraries and resources in a single .jar in order to share our application, if our code has references to resources using absolute or relative paths to the files in our working directory like for example:

ImageIcon image = new ImageIcon('/gui/images/logo.png');

We won't be able to get this resource when executing our standalone .jar file. We'll have to use the getResource() method from the class. Imagine that we are using Swing for creating a cool GUI for our application. Now we want to view our custom logo in our JFrame class instead the default one. And, of course, we want this to be working even when we distribute our app in a single .jar package. If our logo were located at /src/gui/images/logo.png,  this is the code that we'll be using for our purpose inside the JFrame class:

private void customize()
{
    try
        {
            URL res = getClass().getResource("/gui/images/logo.png");
            ImageIcon image = new ImageIcon(res);
            setIconImage(image.getImage());
        }
        catch (Exception ex)
        {
            System.err.println(ex);
        }
}

The same way for any other resources like files or music :).

Enjoy.

Posted on October 28, 2011 at 10:54 by Samuel · Permalink
In: Java, Languages · Tagged with: ,

Please leave a reply :)

Time limit is exhausted. Please reload CAPTCHA.