简体   繁体   English

如何更改给定行和索引处单元格的背景颜色?

[英]how can I change the background color of a cell at a given row and index?

I can't believe I can't find while googling. 我不敢相信在谷歌搜索时找不到。 Every JTable I programmed was automatically filled with data from DB and any editing was done through listeners, but now for testing purposes I just have a simple 3x3 table and I have no idea how to manually select a cell in code (in order to change bg color for testing purposes), something like table.cellAt(1,1).setBGcolor... 我编写的每个JTable都会自动填充数据库中的数据,并且所有编辑都是通过侦听器完成的,但是现在出于测试目的,我只有一个简单的3x3表,而且我不知道如何手动选择代码中的单元格(以更改bg颜色以进行测试),例如table.cellAt(1,1).setBGcolor ...

EDIT: Since title was not formed as a question, How do I manually select a cell in my code? 编辑:由于标题不是一个问题,因此,如何在代码中手动选择一个单元格?

How do I manually select a cell in my code? 如何在代码中手动选择一个单元格?

table.changeSelection(row, column, false, false) , for example table.changeSelection(row, column, false, false) 例如

So your question is rather "how can I change the background color of a cell at a given row and index?". 因此,您的问题是“如何更改给定行和索引处单元格的背景颜色?”。

The background color of a cell depends on the renderer associated to the cell. 单元的背景颜色取决于与该单元关联的渲染器。 But you can't associate a renderer to a cell. 但是您不能将渲染器与单元关联。 What you can do is 你能做的是

  • create a JTable subclass and override getCellRenderer(int row, int column) to return your own renderer 创建一个JTable子类并重写getCellRenderer(int row, int column)以返回您自己的渲染器
  • call setDefaultRenderer(Class columnClass, TableCellRenderer renderer) to associate a renderer to a given class of data 调用setDefaultRenderer(Class columnClass,TableCellRenderer renderer)将渲染器与给定的数据类关联

So, if you want to change the background color of a given cell, you must configure your table to use a custom renderer, and you must configure this custom renderer to use your background color instead of the default one for this given cell (or change the value of the data in this particular cell so that your custom renderer knows it must use the background color). 因此,如果要更改给定单元格的背景色,则必须将表配置为使用自定义渲染器,并且必须将此自定义渲染器配置为使用背景色,而不是此给定单元格的默认颜色(或更改此特定单元格中数据的值,以便您的自定义渲染器知道它必须使用背景色)。

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

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