Question

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.

Was it helpful?

Solution 3

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;
}
}

OTHER TIPS

Check the signature of the .getTableCellRendererComponent(...) method: you're getting a reference to the JTable (from which you can get the TableModel), and the index of the current row and column.

Using those you can look up any relative value you want.

As shown here, you can override prepareRenderer() to affect entire rows.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top