MultiThreaded Programming  «Prev  Next»

Modify Slideshow Applet using Threads - Exercise

Automating the SlideShow Applet

Objective: Modify the SlideShow applet from the previous module so that the images are automatically displayed in succession.

Instructions

Modify the SlideShow applet from the previous module so that it uses a timed thread to automatically flip through the slide show images.
The applet class should implement the Runnable interface to support the thread. The timing of the thread should be established by an applet parameter named waitPeriod, in which the user provides the period of time between slides, in seconds. Remember, the sleep() method accepts milliseconds, so you will need to multiply the value specified by the waitPeriod parameter by 1000 before passing it to sleep().
Following are the main design steps for the applet:

  1. Create member variables named thread and waitPeriod that contain a Thread object and the integer wait period, respectively
  2. Get the wait period for the slide show as an applet parameter named waitPeriod
  3. Override the applet's start() method in order to create the Thread object and get it started
  4. Implement the run() method in the applet and use it to wait a period of time and then move to the next slide. Remember, if the waiting period is specified in seconds in the HTML file, then it should be multiplied by 1000 to convert it to milliseconds before passing it to sleep()
  5. Override the update() method in order to eliminate flicker when drawing each frame
  6. Remove the mouse handling event code since it is no longer necessary for the user to control the slide show
Following is the code required to put the thread to sleep and in the process catch any exceptions. This code should be placed in the run method:

try {
  Thread.sleep(waitPeriod * 1000);
}
catch (InterruptedException e) {
  break;
} 

You have the skills to carry out all of these steps except the overridden update() method. The default behavior for update() is to clear the applet to its background color and then call paint().
Because each slide in the show is the same size, clearing the applet is unnecessary. Therefore, the overridden update() method can simply call paint().
Here's the update() method you should use:


public void update(Graphics g) {
  // Eliminate flicker by not erasing the background
  paint(g);
}

Source Files

We have supplied the source files in the download file available from the Resources page. The specific files for this exercise can be found in the 04-06 folder.

Exercise Scoring

The full credit for this exercise is 15 points. To receive full credit, you will need to successfully modify the source code for the SlideShow applet. You will submit your modified source code.

What to submit

In the text box below, cut and paste the modified source code for the SlideShow applet. Click, Submit to submit the code.