Java Reference
In-Depth Information
or
Image img = getImage (getCodeBase (), "anImage.gif");
In the latter case the Applet class method getCodeBase() provides the web
address for the location of the applet's class file. The file name in the second
parameter is then appended to the codebase and this combined address is used to
locate the image file.
To load an image from within an application, as opposed to an applet, you can
use
Image img = Toolkit.getDefaultToolkit ().getImage ( URL or
filename);
Here the method parameter is either a java.net.URL or a String contain-
ing the filename of the image file. The Toolkit is a class in the java.awt
package that provides various resources and tools for the graphics system.
One of the Toolkit methods is getImage() ,which functions much like the
Applet.getImage() method. It is overloaded to take either a String file-
name parameter specifying the location of the image file or a URL parameter iden-
tifying the image file. (See Chapter 13 for information about the java.net.URL
class.) Before calling getImage() , one must have a reference to the Toolkit
instance in use. The static method Toolkit.getDefaultToolkit() returns
a reference to that Toolkit .
Yo u can obtain an image from a JAR file by using the static getResource()
method from the Class class. This takes advantage of the class loader in the
JVM that reads in a class and loads it for running. The class loader knows how to
load files so it can also be used for loading image files and other resources. For
example, if you were running an application named YourApp ,you could obtain
an image as follows:
URL url = YourApp.class.getResource ("myPhoto.gif");
Image img = Toolkit.getDefaultToolkit ().getImage (url);
Or you could just use this.getClass() to get the Class of the current object:
URL url = this.getClass ().getResource ( " myPhoto.gif " );
Image img = Toolkit.getDefaultToolkit ().getImage (url);
Yo u can then draw the image with this method in the Graphics class:
void drawImage (Image img, int x, int y, ImageObserver io);
As we discuss further in Chapter 11, the getImage() method returns imme-
diately. The actual loading of the image does not begin until the program
attempts to draw the image or to obtain the dimensions of the image with the
getWidth() and getHeight() methods. This approach was designed to avoid
slowing a program while waiting for images to arrive over slow network links.
Search WWH ::




Custom Search