It's not a secret anymore!
The moose likes Swing / AWT / SWT and the fly likes CellRenderer on the fly Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "CellRenderer on the fly" Watch "CellRenderer on the fly" New topic

CellRenderer on the fly

Alex Kravets
Ranch Hand

Joined: Jan 24, 2001
Posts: 476
I have a CellRenderer that colors every other row of a table with a different color. What I need is to color some rows with a third color, but this needs to be done on the fly since every time I load a table, a row that needs to be colored in another color will change.
Any suggestions are appreciated.
Here is the renderer:
class StyleColorCellRenderer extends DefaultTableCellRenderer{
public Component getTableCellRendererComponent(JTable table,
Object val,
boolean isSelected,
boolean hasFocus,
int row,
int column){
Component cell = super.getTableCellRendererComponent(table, val, isSelected, hasFocus, row, column);
int rowCount = table.getRowCount();
boolean yellow = true;
if(row % 2 == 0)
cell.setBackground(new Color(255,255,206));
cell.setBackground(new Color(209,210,211));
return cell;

All right brain, you don't like me and I don't like you, but let's just do this one thing so I can get back to killing you with beer.<br /> <br />- Homer Simpson
Nathan Pruett

Joined: Oct 18, 2000
Posts: 4121

How is this third color determined? Can it be determined from the value object that is being passed in?

Write once, run anywhere, because there's nowhere to hide! - /. A.C.
Alex Kravets
Ranch Hand

Joined: Jan 24, 2001
Posts: 476
Actually I already sovled this one. I pass array of integers representing number of rows to CellRenderer, then I check if current row is from array. If it is I color it white, if not I color it alternating colors.
I agree. Here's the link:
subject: CellRenderer on the fly
It's not a secret anymore!