Java Reference
In-Depth Information
The
java.net.URL
class was used to locate a text file on the Internet in Section 14.13. It
can also be used to locate image files and audio files on the Internet. In general, a
URL
object
is a pointer to a “resource” on a local machine or a remote host. A resource can be a file or a
directory.
The
URL
class can be used to locate a resource file from a class in a way that is independent
of the file's location, as long as the resource file is located in the class directory. Recall that
the class directory is where the class is stored. To obtain the
URL
object for a file from a class,
use the following statement in the applet or application:
Directory
.
.
.
Class metaObject =
this
.getClass();
URL url = metaObject.getResource(resourceFilename);
.
.
.
An applet or
application
A resource file
The
getClass()
method returns an instance of the
java.lang.Class
class for the current
class. This instance is automatically created by the JVM for every class loaded into the mem-
ory. This instance, also known as a
meta object
, contains the information about the class file
such as class name, constructors, and methods. You can obtain a
URL
object for a file in the
class path by invoking the
getResource(filename)
method on the meta object. For exam-
ple, if the class file is in
c:\book
, the following statements obtain a
URL
object for
c:\book\image\us.gif
.
meta object
.
.
.
Class metaObject =
this
.getClass();
URL url = metaObject.getResource(
"image/us.gif"
);
.
.
.
C:\book
An applet or
application
image
us.gif
You can now create an
ImageIcon
using
ImageIcon imageIcon =
new
ImageIcon(url);
Listing 18.11 gives the code that displays an image from
image/us.gif
in the class directory.
The file
image/us.gif
is under the class directory, and its
URL
object is obtained using the
getResource
method (line 5). A label with an image icon is created in line 6. The image
icon is obtained from the
URL
object.
L
ISTING
18.11
DisplayImageWithURL.java
1
import
javax.swing.*;
2
3
public class
DisplayImageWithURL
extends
JApplet {