开发者

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开发者_Python百科 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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜