Section 15.5. The Slide-Show Applet


[Page 717 (continued)]

15.5. The Slide-Show Applet

Problem Specification

Let's suppose our slide show will repeatedly display a set of images named "slide0.gif", "slide1.gif", and "slide2.gif". Suppose these images are stored on a Web site at starbase.trincoll.edu and are stored in a directory named in-jjjava/slideshow. This means that our program will have to load the following three URLs:

http://starbase.trincoll.edu/~jjjava/slideshow/slide0.gif http://starbase.trincoll.edu/~jjjava/slideshow/slide1.gif http://starbase.trincoll.edu/~jjjava/slideshow/slide2.gif 


We want our show to cycle endlessly through these images, leaving about 5 seconds after each slide.

User Interface Design

The user interface for this applet does not contain any GUI components. It just needs to display an image every 5 seconds. It can use a simple paint() method to display an image each time it is repainted:

public void paint(Graphics g) {     if (currentImage != null)         g.drawImage(currentImage, 10, 10, this); } 


The assumption here is that the currentImage instance variable will be set initially to null. Each time an image is downloaded, it will be set to refer to that image. Because paint() is called before the applet starts downloading the images, it is necessary to guard against attempting to draw a null image, which would lead to an exception.

Problem Decomposition

One problem we face with this applet is getting it to pause after each slide. One way to do this is to set up a loop that does nothing for about 5 seconds:

for (int k = 0; k < 1000000; k++ ) ;  // Busy waiting 



[Page 718]

However, this isn't a very good solution. As we saw in Chapter 14, this is a form of busy waiting that monopolizes the CPU, making it very difficult to break out of the loop. Another problem with this loop is that we don't really know how many iterations to do to approximate 5 seconds of idleness.

A much better design would be to use a separate timer thread that can sleep() for 5 seconds after each slide. So our program will have two classes: one to download and display the slides, and one to serve as a timer (Figs. 15.10 and 15.11).

Figure 15.10. The SlideShowApplet downloads and displays the images.


Figure 15.11. The Timer class delays the applet thread after each slide.


  • SlideShowApplet. This JApplet subclass will take care of downloading and displaying the images and starting the timer thread.

  • Timer. This class will implement the Runnable interface so that it can run as a separate thread. It will repeatedly sleep for 5 seconds and then tell the applet to display the next slide.

Effective Design: Busy Waiting

Instead of busy waiting, a thread that sleeps for a brief period on each iteration is a better way to introduce a delay into an algorithm.


15.5.1. The SlideShowApplet class

What should we do with the images we download? Should we repeatedly download and display them, or should we just download them once and store them in memory? The second of these alternatives seems more efficient. If an image has already been downloaded, it would be wasteful to download it again.


[Page 719]

Effective Design: Network Traffic

In general, a design that minimizes network traffic is preferable.


So we will need an array to store the images. Our slide show will then consist of retrieving the next image from the array and displaying it. To help us with this task, let's use a nextImg variable as an array index to keep track of the next image. Even though it isn't absolutely necessary, we could use a third variable here, currentImage, to keep track of the current image being displayed. Thus, our applet needs the following instance variables:

private static final int NIMGS = 3; private Image[] slide = new Image[NIMGS]; private Image currentImage = null; private int nextImg = 0; 


What data do we need?


Given these variables, let's now write a method to take care of choosing the next slide. Recall that the paint() method is responsible for displaying currentImage, so all this method needs to do is to update both currentImage and nextImg. This method should be designed so that it can be called by the Timer thread whenever it is time to display the next slide, so it should be a public method. It can be a void method with no parameters, because the applet already contains all the necessary information to display the next slide. Thus, there's no need for information to be passed back and forth between Timer and this method:

public void nextSlide() {     currentImage = slide[nextImg];     nextImg = (nextImg + 1) % NIMGS;     repaint(); } // nextSlide() 


Method design


The method's algorithm is very simple. It sets currentImage to whatever slide is designated by nextImg, and it then updates nextImg's value. Note here the use of modular arithmetic to compute the value of nextImg. Given that NIMGS is 3, this algorithm will cause nextImg to take on the repeating sequence of values 0, 1, 2, 0, 1, 2, and so forth. Finally, the method calls repaint() to display the image.

Java Programming Tip: Modular Arithmetic

Modular arithmetic (x % N) is useful for cycling repeatedly through the values 0, 1, . . . , N - 1.


The applet's init() method will have two tasks:

  • Download and store the images in slide[].

  • Start the Timer tHRead.


[Page 720]

As we discussed, downloading Web resources requires the use of the getImage() method. Here we just place these method calls in a loop:

for (int k=0; k < NIMGS; k++)      slide[k] = getImage(getCodeBase(), "gifs/demo" + k + ".gif"); 


Note here how we convert the loop variable k into a String and concatenate it right into the URL specification. This allows us to have URLs containing "slide0.gif", "slide1.gif", and "slide2.gif". This makes our program easily extensible should we later decide to add more slides to the show. Note also the use of the class constant NIMGS as the loop bound. This too adds to the program's extensibility.

Java Programming Tip: Concatenation

Concatenating an integer value (k) with a string lets you create file names of the form file1.gif, file2.gif, and so on.


The task of starting the Timer thread involves creating an instance of the Timer class and calling its start() method:

Thread timer = new Thread(new Timer(this)); timer.start(); 


Note that Timer is passed a reference to this applet. This enables Timer to call the applet's nextSlide() method every 5 seconds. This programming technique is known as callback, and the nextSlide() method is an example of a callback method (Fig. 15.12).

Figure 15.12. Timer uses the nextSlide() method to call back the applet to remind it to switch to the next slide.


Java Programming Tip: Callback

Communication between two objects can often be handled using a callback technique. One object is passed a reference to the other object. The first object uses the reference to call one of the public methods of the other object.


This completes our design and development of SlideShowApplet, which is shown in Figure 15.13.

Figure 15.13. The SlideShowApplet class.
(This item is displayed on page 721 in the print version)

import java.awt.*; import javax.swing.*; import java.net.*; public class SlideShowApplet extends JApplet  {     public static final int WIDTH=300, HEIGHT=200;     private static final int NIMGS = 3;     private Image[] slide = new Image[NIMGS];     private Image currentImage = null;     private int nextImg = 0;     public void paint(Graphics g) {         g.setColor(getBackground());         g.fillRect(0, 0, WIDTH, HEIGHT);         if (currentImage != null )             g.drawImage(currentImage, 10, 10, this);     } // paint()     public void nextSlide() {         currentImage = slide[nextImg];         nextImg = (nextImg +  1) % NIMGS;         repaint();     } // nextSlide()     public void init() {         for (int k=0; k < NIMGS; k++)             slide[k] = getImage(getCodeBase(), "gifs/demo" + k + ".gif");         Thread timer = new Thread(new Timer(this));         timer.start();         setSize( WIDTH, HEIGHT );     } // init() } // SlideShowApplet class 

15.5.2. The Timer Class

The timer thread


The Timer class is a subclass of Thread and therefore must implement the run() method. Recall that we never directly call a thread's run() method. Instead, we call its start() method, which automatically calls run(). This particular thread has a very simple and singular function. It is to call the nextSlide() method of the SlideShowApplet class and then sleep for 5 seconds. So its main algorithm will be:


[Page 721]

while (true) {      applet.nextSlide();      sleep( 5000 ); } 


However, recall that Thread.sleep() throws the InterruptedException. This means that we will have to embed this while loop in a try/catch block.

To call the applet's nextSlide() method, we also need a reference to the SlideShowApplet, so we need to give it a reference, such as an instance variable, as well as a constructor that allows the applet to pass Timer a reference to itself.

Given these design decisions, the complete implementation of Timer is shown in Figure 15.14. To see how it works, download it from the Java, Java, Java Web site and run it.

Figure 15.14. The Timer class.
(This item is displayed on page 722 in the print version)

public class Timer implements Runnable {     private SlideShowApplet applet;     public Timer( SlideShowApplet app ) {         applet = app;     }     public void run() {         try {             while ( true ) {                 applet.nextSlide();                 Thread.sleep( 5000 );             }         } catch (InterruptedException e) {             System.out.println(e.getMessage());         }     } // run() } // Timer class 

Self-Study Exercise

Exercise 15.6

Describe the design changes you would make to SlideShowApplet if you wanted to play a soundtrack along with your slides. Assume that the sounds are stored in a sequence of files, "sound0.au", "sound1.au", and so forth, on your Web site.




Java, Java, Java(c) Object-Orienting Problem Solving
Java, Java, Java, Object-Oriented Problem Solving (3rd Edition)
ISBN: 0131474340
EAN: 2147483647
Year: 2005
Pages: 275

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net