Create Software Components 

Using Java Level 2

 

 

Course Info

Scheme

Resources

Tutorials

Java Demos

Utilities

Links


 

 

    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.

 

  1. 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.

  2. 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);
  }

}

  1. You must replace the name of the image file that I used with the name of your image file.

  2. Don't forget to create three files for this applet.  Your .java source code file, your .class file and a HTML file.  

  3. Run your applet using appletviewer or in a browser.

 

Now let's add sound

 

  1. Add the following method to your source code...

public void start() {
    play (getCodeBase(),"dedodedo.wav");
}

  1. You must replace the name of the sound  file that I used with the name of your sound file.

  2. 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!

 

 

 

  Site Home 

Java Home   

  Forum  

Course Info

Welcome

Overview

Assessment

Qualification

Scheme of Work

Assignments

Resources

Information

Blackboard

Learning Center

Web Materials

Reading

Java Demos

Utilities

Links

Lecture Materials

Tutorials & Notes

Exercises

Activities

Quizzes

 

Site Home

Top

Unit Home

ADR 2002