TableCellRenderer using data from another cell

I have jTable1 with 2 columns. I want to control column 1 look, so I use the folowing code to set text font in cells bold or not based on if the cells row is even or odd.

import java.awt.Component;
import java.awt.Font;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

public class CustomTableCellRenderer extends DefaultTableCellRenderer{
@Override
public Component getTableCellRendererComponent (JTable table, Object obj,
        boolean isSelected, boolean hasFocus, int row, int column) {
    Component cell = super.getTableCellRendererComponent(
        table, obj, isSelected, hasFocus, row, column );
        if (row % 2 == 0){
            cell.setFont(getFont().deriveFont(Font.BOLD));
        }
        return cell;
    }
}

I call it using:

jTable1.getColumnModel().getColumn(1).setCellRenderer(new 
CustomTableCellRenderer());

What I want is to modify this TableCellRenderer so that the cells background will be painted based on the other column (column 0) value on the same row. For example if value on column0, row 5 is “book” then column1, row 5 cell will be red, and if column0 value is “newspaper” then column1 color is green. My problem is I don’t know how to pass the column0 value to the column1 renderer so it will be used to change colors.

Answer

I found how to access another column data:

import java.awt.Component;
import java.awt.Font;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

public class CustomTableCellRenderer extends DefaultTableCellRenderer{
@Override
public Component getTableCellRendererComponent (JTable table, Object obj,
    boolean isSelected, boolean hasFocus, int row, int column) {
Component cell = super.getTableCellRendererComponent(
    table, obj, isSelected, hasFocus, row, column );

    //I USE THIS TO ACCESS THE DATA FROM ANOTHER CELL!!!
    TableModel model = table.getModel();
    String media= (String) model.getValueAt(row, 0)


    if (row % 2 == 0){
        cell.setFont(getFont().deriveFont(Font.BOLD));
    }


   //SO I GET THE RESULT I WANT
   if ("book".equals(media)){
     cell.setBackground(Color.red)  
   }
   else{
     cell.setBackground(Color.green)
   }  



    return cell;
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *