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
Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.
Related Posts
- Survey: 83% of Enterprises See Unexpected Benefits from Cloud Computing
- Microsoft Begins Public Beta for Project Oxford Machine Learning Tools
- Microsoft Announces Azure IoT Suite, Container Service, Security Center
- Google Opens European Machine Learning Lab
- Calculate the Distance Between Two Coordinates in C#























