Hi what i am trying to do here is highlight a particular cell in a table using a custom cell renderer. And by the way this is my first cell renderer so i am really not sure what to do! ok now here is the renderer I have written and what I want it to do is highlight the cell at the 1st row of the column through which I call it. But it does not seem to do it, all it does is highlight all the rows in that column once I click a particular cell. Please help me with it.

public class CustomTableCellRenderer extends DefaultTableCellRenderer{
          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 == 1) {
              cell.setBackground(Color.cyan);
      }
      return cell;
    }
  }

Have your class extend something like a JLabel, then have your class implement the TableCellRenderer interface. your code should look something like:

public class MyTableCellRenderer extends JLabel implements TableCellRenderer
{
}

You will need to implement the methods required, but the one you are looking for is getTableCellRendererComponent.

public class MyTableCellRenderer extends JLabel implements TableCellRenderer
{ 
	// This method is called each time a cell in a column 
	// using this renderer needs to be rendered. 
	public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, 
		boolean hasFocus, int rowIndex, int vColIndex) 
	{ 
		Color bg = Color.WHITE;
		//set the background of the required cell
		if(rowIndex == 0 && vColIndex == 0)
		{
			bg = Color.BLUE;
		}
		
		setBackground(bg);
		// Configure the component with the specified value 
		setText(value.toString()); 
		// Since the renderer is a component, return itself 
		return this;
	}
}

You can try using this code, however I have not tested it, but it should give you an idea.

Thanks a lot for your help, I did it without using TableCellRenderer using the following method at the time of creating the table. Thanks anyway :)

public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
			{
                         Component c = super.prepareRenderer(renderer, row, column);
                         if (!c.getBackground().equals(getSelectionBackground()))
                         {
                             String type = (String)getModel().getValueAt(row, column);
                             c.setBackground( type.equals(Calculations.smax) ? Color.GREEN :type.equals(Calculations.smin) ? Color.YELLOW:Color.white );
                         }
                         return c;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.