Posts Tagged ‘JAR’

October 28th, 2011  Posted at   Java, Languages
,    |   No Comments

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.