Question

I have a folder called Etc which has an image I want to use in another file in the same folder, Example.java. So I have Etc\image.png and Etc\Example.java. I've tried using "Etc/image.png" as the image path, but that didn't work. How should I go about this?

Also, suppose the files were in different packages, how would I do it?

My main .java classes are in a package called Main, for the record.

EDIT:

I used this:

ClassLoader.getSystemClassLoader().getResource("Etc\image.png");

Was it helpful?

Solution

You can use Class.getResource(), which uses the class loader to obtain a URL to the resource. For example:

import java.net.URL;
import javax.swing.ImageIcon;

public class Example {

    public ImageIcon getImage() {
        URL url = Example.class.getResource( "image.png" );
        if( url != null ) {
            return new ImageIcon( url );
        }
        return null; // TODO: Better error handling
    }

}

The important part is Example.class.getResource( "image.png" ) - the image path is specified relative to the named class; in this case, it's in the same directory as the class file. You could also use this line in any other class, leaving the reference to Example.class intact.

OTHER TIPS

First things first.

Is Etc a package? In other words at the top of your Example file do you have a

package Etc;

???

Usually package names are lower case, which is why I ask.

Second, although you can use relative paths to access resources, I would recommend always using absolute paths.

So

URL url = Example.class.getResource("/Etc/image.png");

if Etc is a package, otherwise

URL url = Example.class.getResource("/image.png");

if it is not.

For that to work, you have to have the directory where Etc is in the classpath. If it is inside the jar, I don't remember if . works as a classpath, if not, add Etc to the classpath, and reference the image without the classpath, or put Etc in a sub directory. and put that sub directory in the class path.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top