2

I cant find the answer to this anywhere - i am sure it is really simple but im quite confused!

i want to change the colour of the cell background when the value changes. I have written a cell renderer below:

public class CyanTableCellRenderer extends DefaultTableCellRenderer {

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

    cell.setBackground( Color.CYAN );
    return cell;
}
}

I want to pass the value of the cell from the event in the listener - to highlight the cell.

Can anyone help?

Josh
  • 818
  • 2
  • 16
  • 27
  • http://docs.oracle.com/javase/tutorial/uiswing/components/table.html – kleopatra Feb 28 '12 at 15:52
  • I couldnt find anything that could help me there - i want to do something like: table.setCellBackground(int row, int col, Color col) – Josh Feb 28 '12 at 16:10
  • 1
    read again - particularly the paragraphs about renderer :-) That's the swingish way of doing a "tableCellBackground" – kleopatra Feb 28 '12 at 16:16

2 Answers2

2

1) I don't undarstand what's i have a tableModelListener that works. to do with Renderer, maybe you have to mentioned that

2) you can use preparedRenderer, for example

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • i have removed the ambuguity of the listener comment. I cant see how i can use the prepared renderer and pass the cell row and column values to highlight? – Josh Feb 28 '12 at 15:34
2

As suggested by @mKorbel, prepareRenderer() can apply changes to any selected renderer. Alternatively, you can condition the color based on the isSelected parameter of your renderer.

if (isSelect) {
    this.setBackground(Color.cyan);
}

If you just want to change the default background color for selected cells, alter the UIManager property Table.selectionBackground early in your program. This will affect all tables during execution.

UIManager.put("Table.selectionBackground", Color.cyan);
trashgod
  • 203,806
  • 29
  • 246
  • 1,045