img
// Close connection to server.
if (stream != null) {
try {
stream.close();
} catch (Exception e) {}
}
}
If an exception is thrown during the download process, the catch block captures the
exception and calls the error( ) method. The finally block ensures that if the file and stream
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.
The Download class employs the Observer pattern by extending Java's built-in Observable
utility class. Extending the Observable class allows classes that implement Java's Observer
interface to register themselves with the Download class to receive change notifications.
Each time the Download class needs to notify its registered Observers of a change, the
stateChanged( ) method is invoked. The stateChanged( ) method first calls the Observable
class' setChanged( ) method to flag the class as having been changed. Next, the stateChanged( )
method calls Observable's notifyObservers( ) method, which broadcasts the change
notification to the registered Observers.
Action and Accessor Methods
The Download class has numerous action and accessor methods for controlling a download
and getting data from it. Each of the pause( ), resume( ), and cancel( ) action methods simply
does as its name implies: pauses, resumes, or cancels the download, respectively. Similarly,
the error( ) method marks the download as having an error. The getUrl( ), getSize( ),
getProgress( ), and getStatus( ) accessor methods each return their current respective values.
The ProgressRenderer Class
The ProgressRenderer class is a small utility class that is used to render the current progress
of a download listed in the GUI's "Downloads" JTable instance. Normally, a JTable instance
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. The ProgressRenderer class shown here
makes that possible. Notice that it extends JProgressBar and implements TableCellRenderer:
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home