Monday, March 1, 2010

Coloring Cells in JTable

There are situations where you need to highlight some of the values in your data. Swing is the most customizable in Java, with its help you can render your JTable with colored values.


To colorize the values in the JTable we have to change its default renderer, and we have to set our renderer for it.
Following code shows how to create our own renderer.

/* TableCellRenderer is the component which we need to implement for coloring table cells the way we want */
class MyRenderer implements TableCellRenderer
{
 public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column)
 {
 // This is the Component that we will return
  JTextField cell=new JTextField();
  // We don't need border for our component
  cell.setBorder(null);
  if(value!=null)
  {
   cell.setText(value.toString());
   //to highlight complete row
   if(row%2==0)
    cell.setBackground(Color.lightGray);
   //to highlight a value
   if(value.toString().contains("+"))
   {
    cell.setBackground(Color.black);
    cell.setForeground(Color.white);
   }
  }
  return cell;
 }
}
And now its the time to set our renderer to our JTable


JTable table=new JTable(data,cols);
table.setDefaultRenderer(Object.class,new MyRenderer());

No comments:

Post a Comment

Ads Inside Post