Home > Articles > Programming > Java

  • Print
  • + Share This
From the author of

From the author of

Create Progress Cells

You create a table component with columns of employee names and the numbers of hours that those employees work per week. In your table component's hours worked column, hours worked range from 0 through 40. (An employee cannot work more than 40 hours in a week because of union rules.) You present a Java program to your boss that displays your table component of employee names and the hours worked. Although there is nothing wrong with your table component, your boss decides that she would like to see each employee's hours worked expressed as a percentage. No problem! You add a third column that displays percentages. For example, an employee that works 30 hours results in 75% appearing in that employee's percent completed column. Your boss likes what you have done but would also like to see a horizontal bar appear in each percent completed cell, to provide visual feedback. After some work, you end up with Figure 2's table component.

Figure 2 Horizontal bars express hours worked (between 0 and 40) as a percentage.

Now that you know what you are going to do for your boss, how do you make that happen? If you are thinking about using a table component's cell renderer, you are correct. But what kind of renderer should you use? When it comes to horizontal bars, you might want to investigate JProgressBar. A JProgressBar's paint() method "knows" how to render a horizontal bar, with or without percentage text. Because this tip uses JProgressBar to render horizontal bars in cells, I refer to such cells as progress cells. Listing 2 offers source code to a ProgressCells application that uses JProgressBar to render progress cells.

Listing 2: ProgressCells.java

// ProgressCells.java

import java.awt.*;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

class ProgressCells extends JFrame
{
  ProgressCells (String title)
  {
   // Pass the title to the JFrame superclass so that it appears in
   // the title bar.

   super (title);

   // Tell the program to exit when the user either selects Close
   // from the System menu or presses an appropriate X button on the
   // title bar.

   setDefaultCloseOperation (EXIT_ON_CLOSE);

   // Create a custom data model.

   MyTableModel mtm = new MyTableModel ();

   // Create a table using the previously created custom data model.

   JTable jt = new JTable (mtm);

   // Create a renderer for displaying progress cells.

   ProgressCellRenderer pcr = new ProgressCellRenderer ();

   // Get the column model so we can extract individual columns.

   TableColumnModel tcm = jt.getColumnModel ();

   // Assign a progress cell renderer to column 2.

   tcm.getColumn (2).setCellRenderer (pcr);

   // Create an object from an anonymous subclass of
   // TableModelListener. That object's anonymous subclass overrides
   // tableChanged() to test any changes made to hoursWorked, in the
   // table model, by calls to the table model's 
   // setValueAt(Object value, int rowIndex, int colIndex) method.
   // The idea is to validate user entry. (User should enter only 
   // values ranging from 0 through 40 (inclusive).

   TableModelListener tml;
   tml = new TableModelListener ()
      {
        public void tableChanged (TableModelEvent e)
        {
          // Only updates to the table model are to be
          // considered. (Actually, it is not necessary to
          // test against UPDATE because there is no way a
          // table row will be inserted or deleted in this 
          // program as it currently stands.
          // However, in the event that you wish to change the
          // program to allow for dynamic inserts and
          // removals, you might want to leave the following
          // if test.)

          if (e.getType () == TableModelEvent.UPDATE)
          {
            // Obtain the current column index.

            int column = e.getColumn ();

            // Respond to updates that affect the middle
            // column only. (Actually, because only column 1
            // can be updated, the following if test is not
            // necessary. But you might decide to add
            // additional columns in
            // the future that are editable. Or, you might
            // decide
            // to make the leftmost names column editable. 
            // In either situation, the if test is 
            // necessary.)

            if (column == 1)
            {
              // Identify the row containing the cell 
              // whose value changed.

              int row = e.getFirstRow ();

              // The TableModel is needed to identify the
              // current cell's value and change that
              // value, if necessary.

              TableModel tm = (TableModel) e.getSource ();

              // Extract the cell's integer value.

              int i = ((Integer) 
                  (tm.getValueAt (row, column)))
                  .intValue ();

              // If that value is less than 0, change it to
              // 0.

              if (i < 0)
                tm.setValueAt (new Integer (0), row,
                       column);

              // If that value is greater than 40, change
              // it to 40.

              if (i > 40)
                tm.setValueAt (new Integer (40), row,
                       column);
            }
          }
        }
      };

   // Register the table model listener with the table's data model.

   jt.getModel ().addTableModelListener (tml);

   // Place the table in a JScrollPane object (to allow the table to
   // be vertically scrolled and display scrollbars, as necessary).

   JScrollPane jsp = new JScrollPane (jt);

   // Add the JScrollPane object to the frame window's content pane.
   // That allows the table to be displayed within a displayed
   // scroll pane.

   getContentPane ().add (jsp);

   // Establish the overall size of the frame window to 400
   // horizontal pixels by 150 vertical pixels.

   setSize (400, 150);

   // Display the frame window and all contained
   // components/containers.

   setVisible (true);
  }

  public static void main (String [] args)
  {
   // Ensure that the percentage text that appears on a progress bar
   // is white.
   // That is important to the default Java look and feel, which 
   // uses gray. Having the percentage text appear in white instead
   // of gray results in a higher contrast between the text and the
   // bar color.

   UIManager.put ("ProgressBar.selectionForeground", Color.white);
  
   // Create a ProgressCells object, which creates the GUI.

   new ProgressCells ("Progress Cells");
  }
}

class MyTableModel extends AbstractTableModel
{
  // The following private field holds all names for the leftmost
  // column's rows.

  private String [] names =
  {
   "John Doe",
   "Jane Smith",
   "Jack Jones",
   "Paul Finch",
  };

  // The following private field holds all hours worked values for
  // next-to-leftmost column's rows.

  private Integer [] hoursWorked = new Integer [names.length];

  {
   // This instance block initializer is called when a MyTableModel 
   // object is created. It is called just after the default
   // no-argument MyTableModel constructor calls its
   // AbstractTableModel no-argument constructor. (That happens 
   // behind the scenes.)

   for (int i = 0; i < hoursWorked.length; i++)
      hoursWorked [i] = new Integer (0);
  }

  public Class getColumnClass (int columnIndex)
  {
   // By default, every column is assigned an Object type. To
   // ensure that column 1 accepts only integer digits and that
   // column 2's progress cell renderer's getTableCellRenderer()
   // method always receives a value argument of Integer type, 
   // Integer.class returns when columnIndex equals 1 (middle
   // column) or 2 (rightmost column). For consistency, when 
   // columnIndex equals 0 (the leftmost column), String.class 
   // returns.

   switch (columnIndex)
   {
     case 0: return String.class;
     case 1: return Integer.class;
     case 2: return Integer.class;

     // The default case should never be reached. However, the
     // compiler complains without the default.

     default: return Object.class;
   }
  }

  public String getColumnName (int columnIndex)
  {
   // Return an appropriate column name for each columnIndex.

   switch (columnIndex)
   {
     case 0: return "Name";
     case 1: return "Hours worked";
     case 2: return "% worked";

     // The default case should never be reached. However, the
     // compiler complains without the default.

     default: return "";
   }
  }

  public int getColumnCount ()
  {
   // There will be only three columns in this program's table.

   return 3;
  }

  public int getRowCount ()
  {
   // Return names.length rows instead of hard-coding a value because
   // you might want to add entries to the names field. (You will
   // probably not want to add columns, which is why 3 is hard-coded
   // in the previous getColumnCount() method).

   return names.length;
  }

  public Object getValueAt (int rowIndex, int columnIndex)
  {
   // rowIndex should never be equal to or greater than the number 
   // of table rows (as specified by names.length). The following 
   // code is just a safety check. 

   if (rowIndex >= names.length)
     throw new IllegalArgumentException ("" + rowIndex);

   // Return the data at the appropriate rowIndex for each column. 
   // Before Swing calls getTableCellRendererComponent() to return a
   // renderer for column 2, Swing calls getValueAt() with 2 as the
   // columnIndex to obtain the value that it will pass to the
   // getTableCellRendererComponent().

   switch (columnIndex)
   {
     case 0: return names [rowIndex];
     case 1: return hoursWorked [rowIndex];
     case 2: return hoursWorked [rowIndex];

     // The default case should never be reached. However, the
     // compiler complains without the default.

     default: return null;
   }
  }

  public boolean isCellEditable (int rowIndex, int columnIndex)
  {
   // Allow only the middle column (columnIndex equals 1) to be
   // editable.

   return (columnIndex == 1) ? true : false;
  }

  public void setValueAt (Object v, int rowIndex, int columnIndex)
  {
   // rowIndex should never be equal to or greater than the number 
   // of table rows (as specified by names.length). The following 
   // code is just a safety check. 

   if (rowIndex > names.length)
     throw new IllegalArgumentException ("" + rowIndex);

   // Set the value at the appropriate rowIndex for column 1. Only 
   // that column needs to be checked because isCellEditable(int 
   // rowIndex, int columnIndex) identifies that column as editable.
   // Once the value has been set, Swing is told to fire a 
   // TableModelEvent object to all TableModelListener objects (so
   // validation can be performed). (After all, we allow the user to 
   // enter only values from 0 through 40, inclusive). That task is 
   // accomplished by making a call to 
   // fireTableCellUpdated(rowIndex, columnIndex);.

   switch (columnIndex)
   {
     case 1: hoursWorked [rowIndex] = (Integer) v;
         fireTableCellUpdated (rowIndex, columnIndex);
   }
  }
}

class ProgressCellRenderer extends JProgressBar 
              implements TableCellRenderer
{
  ProgressCellRenderer ()
  {
   // Initialize the progress bar renderer to use a horizontal
   // progress bar.

   super (JProgressBar.HORIZONTAL);

   // Ensure that the progress bar border is not painted. (The
   // result is ugly when it appears in a table cell.)

   setBorderPainted (false);

   // Ensure that percentage text is painted on the progress bar.

   setStringPainted (true);
  }

  public Component getTableCellRendererComponent (JTable table,
                          Object value,
                          boolean isSelected,
                          boolean hasFocus,
                          int row,
                          int col)
  {
   if (value instanceof Integer)
   {
     // Ensure that the nonselected background portion of a
     // progress bar is assigned the same color as the table's 
     // background color. The resulting progress bar fits more
     // naturally (from a visual perspective) into the overall 
     // table's appearance.

     setBackground (table.getBackground ());

     // Save the current progress bar value for subsequent
     // rendering. That value is converted from [0, 40] to 
     // [0, 100].

     int i = ((Integer) value).intValue ();
     setValue ((int) (i * 5.0 / 2.0));
   }

   return this;
  }
}

ProgressCells is a large program and probably looks intimidating when you first examine its source code. That source code reveals the creation of a custom model (MyTableModel) and a custom renderer (ProgressCellRenderer). If you are feeling intimidated, remember that the best way to understand something is to divide it into smaller parts and examine each part separately. For that reason, I will first explore the custom model.

ProgressCells creates a custom model from a subclass of the AbstractTableModel class. It does that to provide maximum control over the model. One area where control is desirable involves the getColumnClass() method.

AbstractTableModel supplies a method called getColumnClass(). That method takes an integer argument that identifies a column index and returns the type of data (as a Class object) that can be stored in that column's cells. By design, getColumnClass() always returns Object.class. Is that return value useful? The answer is yes. getColumnClass()'s return value influences the table component regarding the editor that it chooses to edit a cell's value. When getColumnClass() returns Object.class for a certain column, the editor that the table component uses to edit that column's cells allows any character to be entered. That is not a good editor to use when entering numeric data, however. By changing getColumnClass()'s return value to Integer.class for a column that should accept only integers, the table component is forced to use an editor that allows only digits (and the minus sign) to be entered. Furthermore, by overriding getColumnClass() to return specific Class objects, you can choose what editor to use (within the limits of the table component's predefined editors). That is why it is possible to enter only digits and the minus sign in column 1's cells.

Another area of desirable control is whether cells can be edited. You accomplish that task by overriding AbstractTableModel's isCellEditable(int rowIndex, int colIndex) method. If that method returns true, the table component will allow the cell at (rowIndex, colIndex) to have its contents edited. Otherwise, it is not possible to edit the cell—the cell is read-only.

A third area of desirable control involves JTable's getValueAt(int rowIndex, int columnIndex) and setValueAt(int rowIndex, int columnIndex) methods. Whenever a table component needs to retrieve a cell's value, it calls the model's getValueAt(int rowIndex, int columnIndex) method. The table component calls that method just before it calls a renderer's getTableCellRendererComponent() method (to obtain a renderer for the cell). In fact, the value passed to getTableCellRendererComponent() is obtained from getValueAt(int rowIndex, int columnIndex). Also, when you change a cell's value by way of an editor, the table component calls setValueAt(int rowIndex, int columnIndex) to store that value within the model. After storing the value, it is a good idea for setValueAt(int rowIndex, int columnIndex) to call fireTableCellUpdated (rowIndex, columnIndex);. That method call causes all model listeners to receive table component model events. ProgressCells uses that capability to validate an integer—to ensure that it fits within the range 0 through 40.

Now that you are acquainted with the highlights of ProgressCells's custom model, it is time to look at a few things in regard to the renderer. The source code reveals a class called ProgressCellRenderer. That class subclasses JProgressBar and implements the TableCellRenderer interface. As such, it serves as a renderer. ProgressCells attaches a ProgressCellRenderer object to column 2 (the third column because column numbering starts at 0) of the JTable object referenced by jt. The ProgressCellRenderer constructor initializes the renderer so that it has a horizontal orientation, does not paint a border around the progress bar (which looks ugly in the context of a cell), and paints percentage text (such as 75%) on the bar. Just before the table component must render a progress bar, it calls ProgressCellRenderer's getTableCellRendererComponent() method to return a reference to the previously initialized JProgressBar (in the ProgressCellRenderer subclass's constructor).

Within getTableCellRendererComponent(), verification is made to ensure that the type of the value that specifies the length of the progress bar is Integer. Assuming that to be the case, the background color is set to the table component's background color (to ensure a consistent background appearance) and the integer value is retrieved from the Integer object. Because that value ranges between 0 and 40 (inclusive), it is converted to a value ranging from 0 through 100 (inclusive) before being stored in the ProgressCellRenderer object's JProgressBar superclass (by way of setValue(int value)). A reference to the current ProgressCellRenderer object returns. Its paint() method will be called to perform all subsequent rendering. And that is how you create a progress cell.

  • + Share This
  • 🔖 Save To Your Account