简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM