简体   繁体   English

更改 JTable 单元格背景 colors

[英]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.好吧,这是我最后一个问题的后续: JTable:单击按钮时更改单元格背景我现在可以使用 isSelected 参数更改 JTable 中选定单元格的背景颜色,但我无法弄清楚逻辑让单元格渲染器在每次渲染时设置某些单元格的背景。

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.然后,您的 CellRenderer 在决定使用什么颜色作为背景时将需要参考该信息。

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.您必须将包含颜色的复杂 object 作为单元格值传递。

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.改变对象的颜色后,调用table.cellChanged()(不记得方法名)触发重绘。

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类似的东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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