GeeCON Prague 2014*
The moose likes Swing / AWT / SWT and the fly likes JTable cells Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "JTable cells" Watch "JTable cells" New topic
Author

JTable cells

Ravi Kotaru
Greenhorn

Joined: Nov 09, 2003
Posts: 27
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.


ravi<br />scjp 1.4
Vikalp Setya
Greenhorn

Joined: May 10, 2003
Posts: 18
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


Regards,<br />vikalps
Ravi Kotaru
Greenhorn

Joined: Nov 09, 2003
Posts: 27
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: JTable cells