Loading Images as Resources

Up until now, we've loaded images by hardcoded URLs or file names. The Java Development Kit provides another method of loading resources that which is independent of the actual path or URL of the resource.

java.lang.Class provides two methods for loading resources:

  • URL getResource(String)

  • InputStream getResourceAsStream(String)

Both methods delegate to the applet's class loader in order to load the resource. It should be noted that resources are not limited to images, for instance, audio clips can may be accessed as resources.

The benefit to loading an image as a resource stems from the fact that the image does not have to reside in a well-known location. For instance, consider the manner in which an image was loaded ...

Get Graphic Java™ 1.2, Volume I: AWT, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.