Class Exercise
Sound
& Image Applet Exercise
|
This
exercise should be carried out after reading the AppletClass&Lifecycle
Tutorial
An
applet can display JPEG and GIF images and play sound. This exercise runs you
through adding an image and sound to an applet. You can view my
example
if you wish. you should note that my example uses an animated
gif. The actual Java code below does not make the image animate.
-
Find
a picture file and a sound file for your applet. Make sure you place
these two files in the same folder as the Java files you are going to
create.
-
Create
an applet using the following code below.
import
java.applet.*;
import java.awt.*;
import java.net.*;
public class SoundandImage extends Applet {
Image myImage;
public void init() {
myImage = getImage(getCodeBase(), "animpequins.gif");
}
public void paint(Graphics g) {
g.drawImage ( myImage, 0, 0, this);
}
}
-
You
must replace the name of the image file that I used with the name of your
image file.
-
Don't
forget to create three files for this applet. Your .java
source code file, your .class file and a HTML
file.
-
Run
your applet using appletviewer or in a browser.
Now
let's add sound
-
Add
the following method to your source code...
public void start() {
play (getCodeBase(),"dedodedo.wav");
}
-
You
must replace the name of the sound file that I used with the name of
your sound file.
-
Recompile
your code and view your applet in the browser.
Note:
You will notice that you cannot stop this music. It would be better if
the sound stops when the applet stops, (when the user goes to a different
page or closes the browser). To do this you would have to change the
code in the start method above, add a stop method and an instance
variable. If you wish to do this, examine my code
and note the differences..
Have
fun!
|