How to change color of JTable row having a particular value
I am trying to change the color of entire row which is having a column of value "FAIL". Here is my code, which is changing only that particular column. But i want to change the entire row.
Can anyone please give me an idea?
Code:
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus,int row,int col)
{
String s = table.getModel().getValueAt(row,col).toString();
if(s.equalsIgnoreCase("Fail")) {
setForeground(Color.red);
}else {
setForeground(null);
}
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus,
row, col);
}
Conditional colouring a date column
I'm not Swing expert but found this solution to colouring a date column if already passed (I have two dates in my table, and I need to colour the one in the 5th column).
I'm sure it can be improved but that really helped me was to consider that rows can be sorted and then you need to convert the row view index to the row model index otherwise you got a NullPointerException.
Code:
public class MyTableCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column){
if (value instanceof String && column == 5) {
try {
row = table.convertRowIndexToModel(row);
String s = table.getModel().getValueAt(row, column).toString();
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm");
Date date = (Date) formatter.parse(s);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
if (cal.before(Calendar.getInstance())) {
setForeground(Color.RED);
} else {
setForeground(null);
}
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
} catch (ParseException e) {
System.out.println("Exception :" + e);
return null;
}
} else {
setForeground(null);
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
}
}
Hope this helps.
Luis