Hi,

I wanted to change the color of the first two rows of a Jtable .How do i achieve that?

I have written the follow:

TableCellRenderer render1 = null;
render1 = new myCellRenderer();

And the renderer is written as :

class myCellRenderer extends DefaultTableCellRenderer implements TableCellRenderer
	{
		
		private static final long serialVersionUID = 1L;
		public myCellRenderer()
		{
			setBackground(Color.gray);
                 }
public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column) 
		 {
			 	System.out.println("Row value is " + row);
		      Component comp = getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
			 	if (row == 0 || row == 1) 
			 	{		
			 		comp.setBackground(Color.blue);
			 	}
				return comp;
		 }
		 
	}

This does not enter the getTableRendererComponent at all.
What am I doing wrong?

Line 12 is going to give you trouble regardless .. change this to super.

Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

As for the other problem, you have set your new renderer as the cell renderer for all the columns?

table.setDefaultRenderer(Integer.class, new myCellRenderer());

or
table.getColumnModel().getColumn(0).setCellRenderer(new myCellRenderer());
table.getColumnModel().getColumn(1).setCellRenderer(new myCellRenderer());

(iterate through the .getColumnModel() list and set the cell renderer)

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.