Home > Articles > Programming > Java

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Color Cells

One of the most important things you can do to aid users who work with your table components is to take advantage of color. By coloring a table component's cells with appropriate colors, your users can quickly identify important data items. For example, in a table component that shows customer names and credit balances, assigning red backgrounds to those cells whose values reflect negative credit balances helps a user quickly determine whether an excessive number of customers have such balances and whether changes must be made to the user's credit policy. Another use for color is to assign the same color to alternate rows in a table component. That practice helps a user keep his eyes on the same row while reading values in that row's cells. Figure 3 illustrates both color benefits.

Figure 3 Coloring cells alerts users to important data items (such as negative credit balances) and helps users keep their eyes on the same row while reading values in that row's cells.

New JTable users often find the task of assigning colors to a table component's cells to be daunting. In reality, that task is not difficult. For a detailed look at how to accomplish that task, study Listing 3's ColoredCells source code.

Listing 3: ColoredCells1.java

// ColoredCells.java

import java.awt.*;

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

class ColoredCells extends JFrame
  ColoredCells (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 default table model consisting of headers columns
   // and 5 rows.

   String [] headers = { "Name", "Balance" };

   DefaultTableModel dtm = new DefaultTableModel (headers, 5);

   // Populate all cells in the default table model.

   String [] names =
     "John Doe",
     "Jane Smith",
     "Jack Jones",
     "Paul Finch",
     "Susan Smyth"

   double [] balances =

   int nrows = dtm.getRowCount ();
   int ncols = dtm.getColumnCount ();

   for (int i = 0; i < nrows; i++)
      dtm.setValueAt (names [i], i, 0);
      dtm.setValueAt (new Double (balances [i]), i, 1);

   // Create a table using the previously created default table
   // model.

   JTable jt = new JTable (dtm);

   // Create a renderer for displaying cells in certain colors.

   TableRenderer tr = new TableRenderer ();

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

   TableColumnModel tcm = jt.getColumnModel ();

   // For each table column, sets its renderer to the previously 
   // created table renderer.

   for (int c = 0; c < ncols; c++)
      TableColumn tc = tcm.getColumn (c);
      tc.setCellRenderer (tr);

   // 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 200
   // horizontal pixels by 130 vertical pixels.

   setSize (200, 130);

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

   setVisible (true);

  public static void main (String [] args)
   // Create a ColoredCells object, which creates the GUI.

   new ColoredCells ("Colored Cells");

class TableRenderer extends DefaultTableCellRenderer
  private int row, col;

  public Component getTableCellRendererComponent (JTable table,
                          Object value,
                          boolean isSelected,
                          boolean hasFocus,
                          int row,
                          int column)
   // Save row and column information for use in setValue().

   this.row = row;
   this.col = column;

   // Allow superclass to return rendering component.

   return super.getTableCellRendererComponent (table, value, 
                         isSelected, hasFocus,
                         row, column);

  protected void setValue (Object v)
   // Allow superclass to set the value.

   super.setValue (v);

   // If in names column, color cell with even row number white on
   // dark green, and cell with odd row number black on white.

   if (col == 0)
     if (row % 2 == 0)
       setForeground (Color.white);
       setBackground (new Color (0, 128, 0));
       setForeground (UIManager.getColor ("Table.foreground"));
       setBackground (UIManager.getColor ("Table.background"));


   // Must be in balances column. Make sure v is valid.

   if (v == null)
   // Extract the cell's numeric value.

   Double d = (Double) v;

   // If numeric value is less than zero, color cell yellow on red.
   // Otherwise, color cell black on white.

   if (d.doubleValue () < 0)
     setForeground (Color.yellow);
     setBackground (Color.red);
     setForeground (UIManager.getColor ("Table.foreground"));
     setBackground (UIManager.getColor ("Table.background"));

ColoredCells assigns a renderer—an object capable of drawing a component—to each cell that must be colored by carrying out the following tasks in its constructor:

  • Create a TableRenderer object. That object contains everything needed to render one or more cells.

  • Acquire JTable's TableColumnModel object by calling JTable's getColumnModel() method.

  • For each column to which a renderer must be attached, acquire the appropriate TableColumn object by calling TableColumnModel's getColumn() method. A zero-based integer identifying the column to which the renderer must be attached is passed as an argument to the getColumn() method.

  • For each column to which a renderer must be attached, call that column's setCellRenderer() method with a reference to the previously created TableRenderer object.

TableRenderer subclasses DefaultTableCellRenderer (in the package javax.swing.table) and overrides DefaultTableCellRenderer's getTableCellRendererComponent() and setValue() methods. The getTableCellRendererComponent() method returns a Component object whose paint() method performs the rendering and the setValue() method establishes the cell's value to be painted (along with the foreground and background colors used during the painting).

Before Swing paints a cell in a specific column, it calls that column's getTableCellRendererComponent() method. Because ColoredCells assigns a TableRenderer object to each column, Swing calls TableRenderer's getTableCellRendererComponent() method before painting any of the table component's cells. Within getTableCellRendererComponent(), the row and column argument values passed to that method are saved in private fields. Those values will be used to assign colors on a cell-by-cell basis. Once those values have been saved, the superclass (that is, DefaultTableCellRenderer) getTableCellRendererComponent() method is called and a reference to a renderer Component object returns.


How do you know if you should save only the row index or both the row and column indexes? For some programs, you will want to establish a separate renderer for each appropriate column. For other programs, you might want to share a renderer between columns. To distinguish one cell from another when you establish a separate renderer for each column, you need only a cell's row index. You need only that index because the renderer affects only cells in that column. However, to distinguish one cell from another when you share a renderer between columns, you need both a cell's row and column indexes.

DefaultTableCellRenderer's getTableCellRendererComponent() method calls a method named setValue(). Thanks to polymorphism, the setValue() method that gets called is TableRenderer's setValue() method. That method first calls DefaultTableCellRenderer's setValue() method to save the cell's value for rendering. Then calls are made to DefaultTableCellRenderer's setForeground() and setBackground() methods with Color arguments, as appropriate, to establish a cell's foreground and background colors. Once setValue() returns, Swing calls the renderer's paint() method, which retrieves the foreground and background colors before rendering the cell. And that is how you color cells.


When you call setForeground()or setBackground() in setValue(), the selected colors stay in effect until subsequent calls are made to those methods. Without care, you might inadvertently color cells that should not be colored. To prevent that from happening, you should always include calls to the aforementioned methods that set a cell's colors to their look and feel–specific defaults, if that cell is not being colored. You obtain those defaults by calling UIManager.getColor("Table.foreground") and UIManager.getColor("Table.background").

  • + Share This
  • 🔖 Save To Your Account

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.


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.


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.


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.


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


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


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.


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.


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