I am writing a utility that will compare metadata fields from a SQL database. I am able to get all of the data into a JTable. I am trying to now color each particular cell depending on if they match the cell of another JTable. From my understanding I need to write a CellRenderer (Change the color of specific rows in my JTable). I had thought doing something like the below to compare the two values would be the best solution
for(int i=0;i<col2;i++){
for(int j=0;j<row2;j++){
if(table1.getValueAt(i,j).equals(table2.getValueAt(i,j))){
table1.setSelectionBackground(Color.GREEN);
table2.setSelectionBackground(Color.GREEN);
}else if(!(table1.getValueAt(i, j).equals(table2.getValueAt(i, j)))){
table1.setSelectionBackground(Color.RED);
table2.setSelectionBackground(Color.RED);
}
}
}
I know the that the setSelectionBackground is not the method I want to call. I'm confused on how to write the CellRenderer listed in the above post to change the background color of a cell in depending if the contents match each other. Is writing the custom CellRenderer the only option?
EDIT 1: As of right now, it appears to be taking in the correct color for background but it is coloring the entire table rather than a specific cell. Below is my CellRenderer and one of the for loops for how I think I should be calling the setBackground method
private class CellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value,boolean isSelected,boolean hasFocus,int row, int col){
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
this.setOpaque(true);
this.setBackground(table.getBackground());
return this;
}
int col1 = table1.getColumnCount()-1;
int row1 = table1.getRowCount()-1;
int col2 = table2.getColumnCount()-1;
int row2 = table2.getRowCount()-1;
table1.setDefaultRenderer(Object.class, new CellRenderer());
table2.setDefaultRenderer(Object.class, new CellRenderer());
if(row1>row2){
if(col1>col2){
for(int i=0;i<row2;i++){
for(int j=0;j<col2;j++){
if(table1.getValueAt(i,j).equals(table2.getValueAt(i,j))){
color = Color.GREEN;
System.out.println(color);
table1.setBackground(color);
table2.setBackground(color);
}else if(!(table1.getValueAt(i, j).equals(table2.getValueAt(i, j)))){
color = Color.RED;
System.out.println(color);
table1.setBackground(color);
table2.setBackground(color);
}
}
}