Java JTable TableCellRenderer 问题
我在程序中实现了一个名为 scrTbl 的 JTable,我希望能够根据名为“up”的外部布尔变量来改变该表的一列中的文本颜色。我与这项工作相关的代码如下。
TableColumn tcol = scrTbl.getColumnModel().getColumn(9);
tcol.setCellRenderer(new CustomTableCellRenderer());
public class CustomTableCellRenderer extends DefaultTableCellRenderer
{
@Override
public Component getTableCellRendererComponent (JTable table,
Object obj, boolean isSelected, boolean hasFocus, int row, int
column)
{
Component cell = super.getTableCellRendererComponent(table,
obj, isSelected, hasFocus, row, column);
if (up && (row == nmbrStocks))
{
cell.setForeground(Color.green);
}
if ((!up) && (row == nmbrStocks))
{
cell.setForeground(Color.red);
}
return cell;
}//Component
} //class getTableCell...
重点是根据 up 的值将第 9 列和特定行(索引 nmbrStocks)的文本颜色设置为绿色或红色。
但当它运行时,它会将所有文本设置为绿色。每次写入第 9 列中的单元格时是否都会调用渲染器,或者协议是什么?
预先感谢您的任何帮助。
I have implemented a JTable named scrTbl in a program, and I wish to be able to vary text color in one column of this table, based on an external boolean variable called "up". My code related to this effort is as follows.
TableColumn tcol = scrTbl.getColumnModel().getColumn(9);
tcol.setCellRenderer(new CustomTableCellRenderer());
public class CustomTableCellRenderer extends DefaultTableCellRenderer
{
@Override
public Component getTableCellRendererComponent (JTable table,
Object obj, boolean isSelected, boolean hasFocus, int row, int
column)
{
Component cell = super.getTableCellRendererComponent(table,
obj, isSelected, hasFocus, row, column);
if (up && (row == nmbrStocks))
{
cell.setForeground(Color.green);
}
if ((!up) && (row == nmbrStocks))
{
cell.setForeground(Color.red);
}
return cell;
}//Component
} //class getTableCell...
The point is to set the text color for column 9 and a particular row (indexed nmbrStocks) to green or red, based on the value of up.
But when it runs, it sets all of the text green. Is the renderer called each time a cell in column 9 is written to, or what is the protocol?
Thanks in advance for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您只想修改一列,因此调整代码以指定列和行
Since you only want to modify one column, adjust your code to specify the column as well as the row