Soler Mani
Soler Mani

Reputation: 309

Color cells in a column in a JTable

I currently have a JTable consisting of 7 columns and many rows of data.

How would I go about colour each cell in the 7th column? I want to colour according to the data inside the cell.

So if one of the cells in the 7th column was say below 0, then I want to colour red or if one of the cells in the 7th column was more than 0, then colour green etc.

Thank you

Upvotes: 2

Views: 260

Answers (2)

Juvanis
Juvanis

Reputation: 25950

Override prepareRenderer() method when you initialize your table object, put your specific conditionals to change colors accordingly, then color changes will be reflected in your application as you defined. Suppose you have a global JTable variable table and let model be your DefaultTableModel instance:

table = new JTable( model )
{
    public Component prepareRenderer ( TableCellRenderer r, int row, int col )
    {
        Component comp = super.prepareRenderer( r, row, col );
        if ( col == 6 && !isCellSelected( row, col ) )
        {
            if ( table.getValueAt( row, col ) < 0 )
                comp.setBackground( Color.RED );
            else
               comp.setBackground( Color.GREEN );
        }  
        return comp;
    }
};

The code above is checking for col == 6 because you want to colorize 7th column, which corresponds to column index 6 (it starts from 0). In the inner if statement, it is checking for cell values and changing cell background color accordingly.

Upvotes: 2

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103135

You can use a TableCellRenderer to create these custom styles for individual cells in the table. This tutorial explains in some detail. On that page is an example that uses a color renderer which may be the start that you need.

Upvotes: 4

Related Questions