How to set the background color in multiple lines of a JTable?

3

I would like to know how to set the color of the background of multiple rows in the table. In the code below it simply directs the background in just one line, that is, in the last element of the vector. The idea is to pass a list of strings, and the code should set a red background on all rows of the table that contain the same strings as the last list.

public class ColorCellRenderer extends DefaultTableCellRenderer {


private Color color = Color.RED;
private String textToColor;
private List<String> list;

public ColorCellRenderer(){  
    super();  
  }  

public ColorCellRenderer(String string) {
    textToColor = string;

}

public ColorCellRenderer(List<String> list2) {
    list = list2;
}



@Override
public Component getTableCellRendererComponent(JTable table,   
        Object value,  
        boolean isSelected,   
        boolean hasFocus,   
        int row,   
        int column ) {  
    final java.awt.Component cellComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

    for (int c=0; c<list.size(); c++)
    {       

    Object val = table.getValueAt(row, 0);
    String sval = val.toString();
    System.out.println("##"+sval);      

    if (sval.equals(list.get(c))) {
     cellComponent.setForeground(Color.black);
       cellComponent.setBackground(Color.red);
    }
    else {
     cellComponent.setBackground(Color.white);        
     cellComponent.setForeground(Color.black);
        }
    }
    return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
    
asked by anonymous 18.02.2015 / 17:09

1 answer

2

I ended up solving my problem. I changed the repeat loop for this condition.

if (list.contains(val.toString())) {
 cellComponent.setForeground(Color.black);
   cellComponent.setBackground(Color.red);
}
else {
 cellComponent.setBackground(Color.white);        
 cellComponent.setForeground(Color.black);
    }
    
18.02.2015 / 18:16