3
I would like to know how to set the background color of multiple rows of the table. In the code below it simply arrow the background in only 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 from the list passed.
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);
}
See if this helps: How to color specific lines of a Jtable?
– Math
In this case the example you gave me @Math is occurring the same behavior as my code. But thank you very much.
– Maicon Funke
I didn’t get to test your code, but that answer worked properly for me. Are you saying that even using the code of that answer only line of the last element of the vector is being painted?
– Math
Yes. According to the example code, it will paint in red all the lines that have the "red" record, and that is where the problem is. Let’s say I have in a column the lines {car, house, bike, plane} and I want to change the background to red in all lines except "bike". The code won’t work. In my code it is happening the same thing of the example, however I am trying to go through a list of the records of the table
– Maicon Funke