976 Part IV: Applying Java
// This class renders a JProgressBar in a table cell.
class ProgressRenderer extends JProgressBar
implements TableCellRenderer
{
// Constructor for ProgressRenderer.
public ProgressRenderer(int min, int max) {
super(min, max);
}
/* Returns this JProgressBar as the renderer
for the given table cell. */
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column)
{
// Set JProgressBar's percent complete value.
setValue((int) ((Float) value).floatValue());
return this;
}
}
TheProgressRendererclass takes advantage of the fact that Swing’sJTableclass
has a rendering system that can accept “plug-ins” for rendering table cells. To plug into
this rendering system, first, theProgressRendererclass has to implement Swing’s
TableCellRendererinterface. Second, aProgressRendererinstance has to be registered
with aJTableinstance; doing so instructs theJTableinstance as to which cells should be
rendered with the “plug-in.”
Implementing theTableCellRendererinterface requires the class to override the
getTableCellRendererComponent( )method. ThegetTableCellRendererComponent( )
method is invoked each time aJTableinstance goes to render a cell for which this class has
been registered. This method is passed several variables, but in this case, only thevalue
variable is used. Thevaluevariable holds the data for the cell being rendered and is passed
toJProgressBar’ssetValue( )method. ThegetTableCellRendererComponent( )method
wraps up by returning a reference to its class. This works because theProgressRenderer
class is a subclass ofJProgressBar, which is a descendent of the AWTComponentclass.
The DownloadsTableModel Class
TheDownloadsTableModelclass houses the Download Manager ’s list of downloads
and is the backing data source for the GUI’s “Downloads”JTableinstance.
TheDownloadsTableModelclass is shown here. Notice that it extends
AbstractTableModeland implements theObserverinterface:
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
// This class manages the download table's data.
class DownloadsTableModel extends AbstractTableModel
implements Observer
{