Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 33: Creating a Download Manager in Java 975


// Close connection to server.
if (stream != null) {
try {
stream.close();
} catch (Exception e) {}
}
}

If an exception is thrown during the download process, thecatchblock captures the
exception and calls theerror( )method. Thefinallyblock ensures that if thefileandstream
connections have been opened, they get closed whether an exception has been thrown or not.

The stateChanged( ) Method

In order for the Download Manager to display up-to-date information on each of the
downloads it’s managing, it has to know each time a download’s information changes. To
handle this, the Observer software design pattern is used. The Observer pattern is analogous
to an announcement’s mailing list where several people register to receive announcements.
Each time there’s a new announcement, each person on the list receives a message with the
announcement. In the Observer pattern’s case, there’s an observed class with which observer
classes can register themselves to receive change notifications.
TheDownloadclass employs the Observer pattern by extending Java’s built-inObservable
utility class. Extending theObservableclass allows classes that implement Java’sObserver
interface to register themselves with theDownloadclass to receive change notifications.
Each time theDownloadclass needs to notify its registeredObservers of a change, the
stateChanged( )method is invoked. ThestateChanged( )method first calls theObservable
class’setChanged( )method to flag the class as having been changed. Next, thestateChanged( )
method callsObservable’snotifyObservers( )method, which broadcasts the change
notification to the registeredObservers.

Action and Accessor Methods

TheDownloadclass has numerous action and accessor methods for controlling a download
and getting data from it. Each of thepause( ),resume( ), andcancel( )action methods simply
does as its name implies: pauses, resumes, or cancels the download, respectively. Similarly,
theerror( )method marks the download as having an error. ThegetUrl( ),getSize( ),
getProgress( ), andgetStatus( )accessor methods each return their current respective values.

The ProgressRenderer Class


TheProgressRendererclass is a small utility class that is used to render the current progress
of a download listed in the GUI’s “Downloads”JTableinstance. Normally, aJTableinstance
renders each cell’s data as text. However, often it’s particularly useful to render a cell’s data
as something other than text. In the Download Manager ’s case, we want to render each of
the table’s Progress column cells as progress bars. TheProgressRendererclass shown here
makes that possible. Notice that it extendsJProgressBarand implementsTableCellRenderer:

import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
Free download pdf