File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes reading within a sub-folder using ImageIcon ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "reading within a sub-folder using ImageIcon ?" Watch "reading within a sub-folder using ImageIcon ?" New topic

reading within a sub-folder using ImageIcon ?

Jon Camilleri
Ranch Hand

Joined: Apr 25, 2008
Posts: 660

I would like to know whether I can set ImageIcon to read from a relative path, rather, than from the same path where the source code resides. For example my images are located within an images sub-directory relative to the source code. If there is some other way I don't mind knowing either

The following code does not compile it is just to illustrate what I would like to do:

Stephan van Hulst

Joined: Sep 20, 2010
Posts: 3574

You can use Class.getResource() to get resources relative to the class path.
Jelle Klap

Joined: Mar 10, 2008
Posts: 1753

Depending on a path relative to the JVM's current directory isn't really the way to go.
Indeed, classpath resources a better alternative, and there are several ways to go about this.
For instance, using the relevant methods on Class and ClassLoader.
These differ slightly in their behavior though, which can be a bit of a pain.

Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: reading within a sub-folder using ImageIcon ?
Similar Threads
Set my Java application as the default program to open a file extension
Problems dispaying icon
Escape sequences
Cant load images from my jar
null ImageIcon from getResource in jar