Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java JTable change cell color

I would like to make an editable table and then check the data to make sure its valid. Im not sure how to change the color of just one cell. I would like to get a cell, for example (0,0) and color the foreground to red. I have read the other posts on SO as well as Oracle about the custom ColorRenderer, but i just don't get how i would use this.

Thanks.

like image 697
Matt Avatar asked Apr 15 '11 07:04

Matt


2 Answers

@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
        int row, int col) {
    Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
    int control = row;
    control = control % 2;
    control = (control == 0) ? 1 : 0;
    if (control == 1) {
        c.setBackground(Color.green);
    } else {
        c.setBackground(Color.cyan);
    }
    return c;
}
like image 104
carlos ortiz Avatar answered Oct 11 '22 04:10

carlos ortiz


I believe the correct way to do colouring in a table is via a ColorHighlighter. The table renderers have problems to render different colours in the same column.

Here is an example of how to use highlighters. In this case it is for highlighting a cell that is not editable.

public class IsCellEditablePredicate implements HighlightPredicate {

   private JXTable table;

   public IsCellEditablePredicate (final JXTable table) {
       this.table = table;
   }

   @Override
   public boolean isHighlighted(Component component, ComponentAdapter componentAdapter) {

        return !table.isCellEditable(componentAdapter.row,
          componentAdapter.column);
   }
}

and then in your code for setuping the table you add the highlighter and its colour parameters:

 ColorHighlighter grayHighlighter = new ColorHighlighter(new IsCellEditablePredicate(table));

    grayHighlighter.setBackground(Color.LIGHT_GRAY);
    grayHighlighter.setForeground(table.getForeground());
    grayHighlighter.setSelectedBackground(table.getSelectionBackground().darker());
    grayHighlighter.setSelectedForeground(table.getSelectionForeground().darker());

    table.setHighlighters(grayHighlighter);
like image 29
Mateva Avatar answered Oct 11 '22 05:10

Mateva