How to load images in Java

Every once in a while there is a question on the NetBeans mailinglist about how to load an image (or other ressource, like a text file) relative to the executing JAR.

The Java Tutorial gives the answer in the chapter “How to use Icons“: imgURL = getClass().getResource("inSamePackage.png"); imgURL = getClass().getResource("/de/foo/otherPackage.png");

Using relative paths like “../other/foo.png” didn’t seem to work for me.

An alternative is to put all images into a separate resource-JAR so that the images can be changed without needing to repack the executable jar – this is covered in the chapter “Loading Images Using getResource“. Also very important: The chapter “Improving Perceived Performance When Loading Image Icons” which demonstrates the use of asynchronous loading using SwingWorkers (Using SwingWorkers is a very convenient way of using multithreading).