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.
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".
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));
精彩评论