• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JTable cells

 
Ravi Kotaru
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to set background color to some specific cells in my JTable based upon some conditions. I have tried setBackgroundColor() method of TableCellRenderer class. But instead of changing bgcolor of a particular cell say (1,3),the whole table background color is changing.
Can anyone help me on this please. Here is the code I wrote.
 
Vikalp Setya
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
You will have to write a TableCellRenderer for it.
Write a renderer as follows :
class MyColorTableCellRenderer extends DefaultTableCellRenderer {

//this method needs to be overriden to do the stuff
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column)
{
/ *return a Component that meets ur condition
say condition is that alternate columns should have same background color */

JLabel label = new JLabel(String.valueOf(value));
//must
label.setOpaque(true);

if(column %2 == 0)
label.setBackground(Color.cyan);
else
label.setBackground(Color.blue);

//you need to put up a border around the label if isSelected flag is true
if(selected)
label.setBorder(BorderFactory.createEtchedBorder());

return label;

}
}

set an instanceof this class as the renderer for each of table columns
see the API for that. Mail me the code in case of problem at vikalp_setya@rediffmail.com
Regards,
vikalp
 
Ravi Kotaru
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Vikalp,
Thanx very much. I tried it but it didn't work. I am using JTable in an applet. I am sending the code by mail please help me.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic