Home > Articles > Programming > Java

Like this article? We recommend

Like this article? We recommend

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020