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 = { -50000.0, 4000.0, -32.3, 802.5, -128.0 }; 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)); } else { setForeground (UIManager.getColor ("Table.foreground")); setBackground (UIManager.getColor ("Table.background")); } return; } // Must be in balances column. Make sure v is valid. if (v == null) return; // 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); } else { setForeground (UIManager.getColor ("Table.foreground")); setBackground (UIManager.getColor ("Table.background")); } } }
ColoredCells assigns a rendereran object capable of drawing a componentto 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.
TIP
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.
CAUTION
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 feelspecific defaults, if that cell is not being colored. You obtain those defaults by calling UIManager.getColor("Table.foreground") and UIManager.getColor("Table.background").