The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing.table  [62 examples] > Rows  [8 examples]

e914. Shading Rows and Columns in a JTable Component

The simplest way of shading alternate rows or columns in a JTable component is to override the prepareRenderer() method. The table calls this method for every cell, just prior to displaying it. The override should call the superclass and retrieve the prepared component. It can then modify the background and foreground colors to achieve any desired pattern of shaded rows and columns.
    // This table shades every other row yellow
    JTable table = new JTable() {
        public Component prepareRenderer(TableCellRenderer renderer,
                                         int rowIndex, int vColIndex) {
            Component c = super.prepareRenderer(renderer, rowIndex, vColIndex);
            if (rowIndex % 2 == 0 && !isCellSelected(rowIndex, vColIndex)) {
                c.setBackground(Color.yellow);
            } else {
                // If not shaded, match the table's background
                c.setBackground(getBackground());
            }
            return c;
        }
    };
    
    // This table shades every other column yellow
    table = new JTable() {
        public Component prepareRenderer(TableCellRenderer renderer,
                                         int rowIndex, int vColIndex) {
            Component c = super.prepareRenderer(renderer, rowIndex, vColIndex);
            if (vColIndex % 2 == 0 && !isCellSelected(rowIndex, vColIndex)) {
                c.setBackground(Color.yellow);
            } else {
                // If not shaded, match the table's background
                c.setBackground(getBackground());
            }
            return c;
        }
    };

 Related Examples
e907. Getting the Number of Rows and Columns in a JTable Component
e908. Appending a Row to a JTable Component
e909. Inserting a Row in a JTable Component
e910. Removing a Row from a JTable Component
e911. Moving a Row in a JTable Component
e912. Copying a Row or Column in a JTable Component
e913. Setting the Height of a Row in a JTable Component

See also: Cells    Column Heads    Columns    Editing    Events    Layout    Scrolling    Selection    Sorting    Table Model    Tool Tips   


© 2002 Addison-Wesley.