Question

I'm trying to images in Java, and right now I'm using images that are in the local directory and it is working fine. However, it would be nice if I could put the images in a folder and reference the path of the images to draw them, but I've been unable to do that so far.

Right now my code is essentially:

Image theImage = Toolkit.getDefaultToolkit().getImage(path);
g.drawImage(theImage,left,right,component);

And this works fine as long as iconPath is a local path. But I can't figure out how to get it to work for non local paths or subdirectories.

Was it helpful?

Solution

The section from the Swing tutorial on How to Use Icons shows many ways to load an image.

Don't forget you can always use a fully qualified path like "c://java/images/some.gif".

OTHER TIPS

You can use the ImageIO utility class to load images from file paths.

Example:

/* at top of file */
import javax.imageio.ImageIO;
import java.io.File;
/* in your code */
Image theImage = ImageIO.read(new File(path));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top