Java Reference
In-Depth Information
4
public
DisplayImageWithURL() {
5 java.net.URL url =
this
.getClass().getResource(
"image/us.gif"
)
;
get image URL
create a label
6 add(
new
JLabel(
new
ImageIcon(url)
));
7 }
8 }
main
method omitted
If you replace the code in lines 5-6 with the following code,
add(
new
JLabel(
new
ImageIcon(
"image/us.gif"
)));
you can still run the program as a standalone application, but not as an applet from a browser,
as shown in Figure 18.13.
F
IGURE
18.13
The applet loads an image from an image file located in the same directory as the applet.
18.22
✓
✓
How do you create a
URL
object for the file
image/us.gif
in the class directory?
Check
18.23
How do you create an
ImageIcon
from the file
image/us.gif
in the class directory?
Point
The
Applet
class contains the methods for obtaining an
AudioClip
object for an
audio file. The
AudioClip
object contains the methods for playing audio files.
Key
Point
There are several formats for audio files. Java programs can play audio files in the WAV,
AIFF, MIDI, AU, and RMF formats.
To play an audio file in Java (application or applet), first create an
audio clip object
for the file.
The audio clip is created once and can be played repeatedly without reloading the file. To create
an audio clip, use the static method
newAudioClip()
in the
java.applet.Applet
class:
AudioClip audioClip = Applet.newAudioClip(url);
Audio originally could be played only from Java applets. For this reason, the
AudioClip
inter-
face is in the
java.applet
package. Since JDK 1.2, audio can be played in any Java program.
The following statements, for example, create an
AudioClip
for the
beep.au
audio file
in the class directory:
Class metaObject =
this
.getClass();
URL url = metaObject.getResource(
"beep.au"
);
AudioClip audioClip = Applet.newAudioClip(url);