Frank D. Greco  (2002-05-10  02:25):
>[the saga of my re-enty into the GUI world continues...]
>
>I need to set the row color for my subclass of JTable.
>All the example code that I've discovered show how to
>change the color of a *column*.
>
>I thought it would be as easy as:
>
>       x = get the TableCellRenderer for that row,col
>       c = get the Component for that TableCellRenderer
>       c.setForeground(Color.foo)
>       c.setBackground(Color.bar)
>
>But nope...  And I've tried Googling for examples, but nothing
>useful.  Seems pretty obtuse just to change the color of
>a row...
>

You are on the right way, especially when you have already
subclassed the JTable.

What you have to do is to overload the method:
public Component prepareRenderer(TableCellRenderer renderer,
                                 int row,
                                 int column)

There you call the super-class implementation of prepareRenderer,
check if the row is the selected one or not (or you usually do to avoid
removing the blue mark-colour) and if it is not selected, change
the colour on the received component accordingly.
Advantages with this setup is if your table are used by others, it will
change the colour even if the Component is somehting else beside your
own created/default CellRenderer.

Example code:
    public java.awt.Component prepareRenderer(TableCellRenderer renderer, int row, int 
column)
    {
        java.awt.Component cell = super.prepareRenderer( renderer, row, column );
        // We do not want to change the row that is marked, so we check for that
        // first.
        if( !isCellSelected( row, column) )
        {
                     // Used to reset the background colour to white if
            // table is enabled and the cell is editable
            if( isEnabled() && getModel().isCellEditable( row, column ) )
            {
                cell.setBackground( null );
            }
            else
            {
                // If the cell is not editable in anyway, it should have
                // our background colour
                cell.setBackground(UIManager.getColor( OURUI_COLOUR ) );
            }
        }
        return cell;
    }


You should always have in mind that quite a few of the swing components
use caching of their renderers. Ie: in a table, it reuses it's renderer
for more than one cell, so it will reset some stuff like colours for each
drawing.


Yours sincerely
Peter Norell
_______________________________________________
Advanced-swing mailing list
[EMAIL PROTECTED]
http://eos.dk/mailman/listinfo/advanced-swing

Reply via email to