ranonk
ranonk

Reputation: 475

Change JTable cell background colors

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.

Upvotes: 1

Views: 2258

Answers (2)

Penkov Vladimir
Penkov Vladimir

Reputation: 939

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

Upvotes: 2

jzd
jzd

Reputation: 23639

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

Upvotes: 4

Related Questions