JTable Row Color Based on Value of Each Row.

 How to color each row in Java Table. We need to inherit the property of table renderer to do this.

Let’s see how to color the row in table in java.

PROGRAM

import java.awt.Color;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Mukesh
 */
public class renderClass extends DefaultTableCellRenderer {
    

DefaultTableModel model=null;

   public renderClass(JTable jtable) {
      super();
     
      model=(DefaultTableModel)jtable.getModel();
      
   }
@Override
   public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,   boolean hasFocus, int row, int column) {
      Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(Double.parseDouble(model.getValueAt(row,1).toString())>=0)
{
     cell.setForeground(Color.green);    
      return cell;
}
else
{ cell.setForeground(Color.red);    
      return cell;
    
}

   }


}
Let's see how to apply this in our table.
TableColumn tColumn = jTable.getColumnModel().getColumn(1);
tColumn.setCellRenderer(new renderClass(jTable));
jScrollPane.setViewportView(jTable);

First get the column you want to set foreground color.

Next set the cell Renderer.

Next Refresh the table.

I hope you have learned how to color each row in java table.

Thank you,

Mukesh Mohanan

Comments

Popular posts from this blog

Create Option Chain using PYTHON.

How to Place Order in Zerodha using Python

How to place order in zerodha when RSI crosses below 30? Algo Trading Python