1

Alright this is a follow-up to my last question: JTable: Changing cell background when a button is clicked I can now change background color of selected cells in the JTable by using the isSelected parameter, but I can't figure out the logic to get the cell renderer to set the backgrounds of certain cells every time it renders.

Basically I want to selected a few cells, click a button, change the background color of selected cells, and have it keep that color after I deselect the cell (without effecting the unselected cells).

This seems like such a simple problem, but I am absolutely stumped on how to do this.

As always, any input is appreciated.

Community
  • 1
  • 1
ranonk
  • 445
  • 6
  • 15
  • Here's a related [example](https://sites.google.com/site/drjohnbmatthews/table). – trashgod Jun 28 '11 at 18:43
  • looks like as your two threads talks about prepareRenderer only, because works with (convertRowIndexToModel(int row)) RowFilter, RowSorter, AddRow(s), RemoveRow(s), just carrefully with removes TableColumn(s) from TableView (ArrayIndexException) ... – mKorbel Jun 28 '11 at 19:24

2 Answers2

4

You will need to store information about which cells are selected and the background that is needed. Then your CellRenderer will need to refer to that information when deciding what color to use for the background.

Basic logic for renderer:

  • If selected used selected color
  • If the cell is marked to hold a background color
  • In all other cases use the normal background color
jzd
  • 23,473
  • 9
  • 54
  • 76
  • excellent. I wasn't holding the background in other cases, so all of the cells were taking on that color. Thank you. – ranonk Jun 28 '11 at 21:29
2

You must pass the complex object, containing the color, as cell value.

Pressing the button should update object's color for selected objects (for selected cells in your case). Your renderer must use this value's color to fill background.

After changing object's color, call table.cellChanged() (don't remember the name of method) to trigger repainting.

class CellValue {
 public Color color;
 public String text; 
}

...
//renderer
getCellRendererComponent(...) {
  JLabel l = super.getCellRendererComponent(...);
  CellValue v = (CellValue) value;
  l.setBackgroundColor(v.color);
}

Something like that

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
Penkov Vladimir
  • 921
  • 5
  • 10