我正在使用 netbeans IDE7.4,我在运行时向 JTable
添加行,现在我想为特定行设置背景颜色。
现在的问题是,当该行的值更改时,该特定行的颜色没有更改,而当我向上或向下滚动表格时,应用更改。
如何在运行时刷新表?如何在运行时设置特定行的背景颜色?
这是用于为特定行着色的渲染器类:
public class MyCellRenderer extends javax.swing.table.DefaultTableCellRenderer
{
public java.awt.Component getTableCellRendererComponent(javax.swing.JTable table, java.lang.Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
final java.awt.Component cellComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
Object val=table.getValueAt(row, 2);
String sval=val.toString();
sval=sval.replaceAll(":","");
int ival=Integer.parseInt(sval);
if(ival==0)
{
cellComponent.setForeground(Color.black);
cellComponent.setBackground(Color.red);
}
else
{
cellComponent.setBackground(Color.white);
cellComponent.setForeground(Color.black);
}
if (isSelected)
{
cellComponent.setForeground(table.getSelectionForeground()); cellComponent.setBackground(table.getSelectionBackground());
}
return cellComponent;
}
}
并像这样分配给 jtable :
newViewTable.setDefaultRenderer(Object.class,new MyCellRenderer());
newViewTable 是 JTable 的名称。
最佳答案
how to set background color of particular row at runtime?
使用表格单元格渲染器。参见 How to Use Tables: Using Custom Renderers了解详情。
关于java - 在运行时为 JTable 的特定行设置背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22524879/