更改 JTable 中行的背景颜色
我有一个包含 3 列的 JTable。我已经为所有 3 列设置了 TableCellRenderer
(可能不是很有效?)。
for (int i = 0; i < 3; i++) {
myJTable.getColumnModel().getColumn(i).setCellRenderer(renderer);
}
getTableCellRendererComponent()
返回一个每行具有随机背景颜色的组件。
在程序运行时如何将背景更改为其他随机颜色?
I have a JTable with 3 columns. I've set the TableCellRenderer
for all the 3 columns like this (maybe not very effective?).
for (int i = 0; i < 3; i++) {
myJTable.getColumnModel().getColumn(i).setCellRenderer(renderer);
}
The getTableCellRendererComponent()
returns a Component with a random background color for each row.
How could I change the background to an other random color while the program is running?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Richard Fearn 的回答的简历,使第二行变成灰色:
Resumee of Richard Fearn's answer , to make each second line gray:
一种方法是存储模型中每一行的当前颜色。这是一个固定为 3 列和 3 行的简单模型:
请注意,
setRowColour
调用fireTableRowsUpdated
;这将导致仅更新表的该行。渲染器可以从表中获取模型:
更改行的颜色就像这样简单:
One way would be store the current colour for each row within the model. Here's a simple model that is fixed at 3 columns and 3 rows:
Note that
setRowColour
callsfireTableRowsUpdated
; this will cause just that row of the table to be updated.The renderer can get the model from the table:
Changing a row's colour would be as simple as:
此处给出的其他答案效果很好,因为您在每一列中都使用相同的渲染器。
但是,我倾向于认为,通常在使用 JTable 时,每列中都会有不同类型的数据,因此您不会为每列使用相同的渲染器。在这些情况下,您可能会发现表格行渲染方法有帮助。
本质上,它建议重写 JTable 的prepareRenderer 方法。
The other answers given here work well since you use the same renderer in every column.
However, I tend to believe that generally when using a JTable you will have different types of data in each columm and therefore you won't be using the same renderer for each column. In these cases you may find the Table Row Rendering approach helpfull.
In essence it suggests to override JTable's prepareRenderer method.
这基本上就像重新粉刷桌子一样简单。然而,我还没有找到一种方法来选择性地重新绘制一行/列/单元格。
在此示例中,单击按钮会更改行的背景颜色,然后调用重绘。
This is basically as simple as repainting the table. I haven't found a way to selectively repaint just one row/column/cell however.
In this example, clicking on the button changes the background color for a row and then calls repaint.
对
getTableCellRendererComponent(...)
的调用包含要为其寻找渲染器的单元格的值。您可以使用该值来计算颜色。如果您还使用 AbstractTableModel,则可以向渲染器提供任意类型的值。
获得颜色后,您可以在要返回的组件上
setBackground()
。The call to
getTableCellRendererComponent(...)
includes the value of the cell for which a renderer is sought.You can use that value to compute a color. If you're also using an AbstractTableModel, you can provide a value of arbitrary type to your renderer.
Once you have a color, you can
setBackground()
on the component that you're returning.