Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

986 Part IV: Applying Java


SwingUtilities.invokeLater(new Runnable() {
public void run() {
DownloadManager manager = new DownloadManager();
manager.setVisible(true);
}
});
}
}

The DownloadManager Variables

DownloadManagerstarts off by declaring several instance variables, most of which hold
references to the GUI controls. TheselectedDownloadvariable holds a reference to the
Downloadobject represented by the selected row in the table. Finally, theclearinginstance
variable is abooleanflag that tracks whether or not a download is currently being cleared
from the Downloads table.

The DownloadManager Constructor

When theDownloadManageris instantiated, all of the GUI’s controls are initialized inside
its constructor. The constructor contains a lot of code, but most of it is straightforward.
The following discussion gives an overview.
First, the window’s title is set with a call tosetTitle( ). Next, thesetSize( )call establishes
the window’s width and height in pixels. After that, a window listener is added by calling
addWindowListener( ), passing aWindowAdapterobject that overrides thewindowClosing( )
event handler. This handler calls theactionExit( )method when the application’s window is
closed. Next, a menu bar with a “File” menu is added to the application’s window. Then the
“Add” panel, which has the Add Text field and button, is set up. AnActionListeneris added
to the “Add Download” button so that theactionAdd( )method is called each time the button
is clicked.
The downloads table is constructed next. AListSelectionListeneris added to the table so
that each time a row is selected in the table, thetableSelectionChanged( )method is invoked.
The table’s selection mode is also updated toListSelectionModel.SINGLE_SELECTIONso
that only one row at a time can be selected in the table. Limiting row selection to only one
row at a time simplifies the logic for determining which buttons should be enabled in the
GUI when a row in the download table is selected. Next, aProgressRendererclass is
instantiated and registered with the table to handle the “Progress” column. The table’s row
height is updated to theProgressRenderer’s height by callingtable.setRowHeight( ). After
the table has been assembled and tweaked, it is wrapped in aJScrollPaneto make it scrollable
and then added to a panel.
Finally, the buttons panel is created. The buttons panel has Pause, Resume, Cancel, and
Clear buttons. Each of the buttons adds anActionListenerthat invokes its respective action
method when it is clicked. After creating the buttons panel, all of the panels that have been
created are added to the window.

The verifyUrl( ) Method

TheverifyUrl( )method is called by theactionAdd( )method each time a download is added
to the Download Manager. TheverifyUrl( )method is shown here:
Free download pdf