带排序功能的 JTable 渲染器
我正在尝试使用行排序器对表进行排序。
RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
cTable.setRowSorter(sorter);
我正在使用扩展 DefaultTableCellRenderer 的渲染器。我正在使用渲染器根据单元格的值以某种颜色绘制单元格的内容。
cTable.setDefaultRenderer(Object.class,new <renderer name>());
例如:
public Component getTableCellRendererComponent(JTable table, Object v,
boolean isSelected, boolean hasFocus, int row, int column)
{
super.getTableCellRendererComponent(table, v, isSelected, hasFocus,
row, column);
int k=table.getValueAt(row,column);
if (k >= 0) this.setForeground(Color.red);
}
注意:这只是一个示例代码。没有实际功能。 当我排序时,排序完美发生,但更改颜色的渲染器功能没有发生。有人之前遇到过这个问题吗?请帮忙
I am trying to sort a table using rowsorter.
RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
cTable.setRowSorter(sorter);
I am using a renderer which extends DefaultTableCellRenderer. I am using the renderer to paint the contents of the cell in some color based on its value.
cTable.setDefaultRenderer(Object.class,new <renderer name>());
eg:
public Component getTableCellRendererComponent(JTable table, Object v,
boolean isSelected, boolean hasFocus, int row, int column)
{
super.getTableCellRendererComponent(table, v, isSelected, hasFocus,
row, column);
int k=table.getValueAt(row,column);
if (k >= 0) this.setForeground(Color.red);
}
Note:This is just a sample code.No real functionality.
when i sort, sorting happens perfectly but the renderer functionality of changing the color is not happening. Has anyone faced this issue earlier?Please help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要将渲染器中的逻辑扩展为:
您可能还希望根据每个条件设置背景颜色。这样做的原因是因为
DefaultTableCellRenderer
的作用就像一个“橡皮图章”,依次应用于每个单元格。例如,如果第 5 行第 1 列的单元格的值 k >= 0,那么您将此单元格和所有后续单元格的前景色切换为红色。因此,如果检查失败,显式将其设置回为“正常”前景色非常重要。You need to extend the logic in your renderer to:
You may also wish to set the background colour depending on each condition. The reason for doing this is because the
DefaultTableCellRenderer
acts like a "rubber stamp" which is applied to each cell in turn. If for example, the cell at row 5, column 1 has a value of k >= 0 then you are switching the foreground colour to red for this cell and all subsequent cells. Therefore, it is important to explicitly set it back to the "normal" foreground colour if your check fails.