So i want to compare 2 value from 2 cells on the same row ("Initial Target" and "Result Target") from my table, and if the value is not the same the cell on "Result Target" column will turn red , but my code turn all cell to red, here's the result :
here's what i expect :
here's my code :
tblResult = new JTable(tableModel) {
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
Component comp = super.prepareRenderer(renderer, row, col);
Object value1 = getModel().getValueAt(row, 2);
Object value2 = getModel().getValueAt(row, 1);
if (value1!=value2) {
comp.setBackground(Color.red);
}
else {
comp.setBackground(Color.white);
}
return comp;
}
};
If you are doing if (value1 != value2)
you are just checking whether value1
and value2
have the same reference and here they don't so, this comparison will always return true
.
What you can do instead is cast these objects to String or Integer like this:
String value1 = (String) getModel().getValueAt(row, 2);
String value2 = (String) getModel().getValueAt(row, 1);
And then perform the comparison as follows:
if (!value1.equalsIgnoreCase(value2)) {}
You execute the logic for each columnIndex, so each rendering component has its color manipulated and is painted eg red. You should have some condition around like if(col == 2)
and so only execute your color magic when the method prepareRenderer()
is called for the 3rd column.
Of cause the already mentioned comparison fix if (!value1.equalsIgnoreCase(value2)) {}
should be done.
By the way, you might use table.getColumnModel().getColumn(2).setCellRenderer(TableCellRenderer)
to set a specific rendering logic just for this column.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.