Loading Resources With the getResource() Method

Most nontrivial applications are packaged with “resource files,” which are nothing more than files used by the application for various purposes. Some examples of these resources include image (GIF, JPEG) files, message/text data, configuration/initialization information, and so on. There are several of ways to read these resources, but most of them are closely tied to the way in which the code is packaged. For example, one way will work correctly for a Java application, while another will work only for an applet. Obviously, the most desirable approach is to use a mechanism that functions correctly regardless of the packaging of the code. This is where the getResource() method in java.lang.Class is useful. It returns a URL that represents a resource, which can then be used to read the resource.

In this example, the resource stored in “myimage.gif” is loaded and drawn at the upper left corner of the screen. Note that this code will work regardless of whether or not it is run as an application, an applet, or is included in a Java Archive (JAR) file. For more information, read Accessing Resource in a Location-Independent Manner, which is included in Sun’s documentation provided with the Java Development Kit (JDK).

 import java.awt.*;import java.net.*;public class ResourceTest extends Frame {	Image img;	public ResourceTest() throws Exception {		URL myurl = this.getClass().getResource("/myimage.gif");		Toolkit tk = this.getToolkit();		img = tk.getImage(myurl);	}  //  public ResourceTest()	public void paint(Graphics g) {		g.drawImage(img, 0, 0, this);	}  //  public void paint()}  //  public class ResourceTest extends Frame
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS