更改Jtable中特定单元格中的字体颜色

时间:2014-01-27 06:51:15

标签: java colors jtable foreground cellrenderer

DefaultTableCellRenderer cellRender = new DefaultTableCellRenderer();
for(int i = 0; i < tblPackage.getRowCount(); i++)
{
    if("ACTIVE".equals(tblPackage.getModel().getValueAt(i, 3).toString()))
    {
                cellRender.setForeground(Color.GREEN);
    }
}

我的表中有4列......如果数据的第4列等于“ACTIVE”字,它将变为绿色......我该怎么做?我的逻辑有问题吗?

2 个答案:

答案 0 :(得分:3)

您应该覆盖getTableCellRendererComponent

DefaultTableCellRenderer
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column)
        {
            Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

            if(table.getColumnModel().getColumn(column).getIdentifier()
                    .equals(your_4th_column_identifier)) // or use getColumnAt(4)
            {
                if(value.toString().equals("ACTIVE"))
                {
                    c.setBackground(Color.GREEN);
                }
            }
            return c;
        }

答案 1 :(得分:0)

您可以使用以下内容:

    Jtable jtable = new JTable(dtm)
    {

        public Component prepareRenderer(TableCellRenderer renderer,int row,int column)
        {
              Component comp=super.prepareRenderer(renderer,row, column);
              if(column==3 && "ACTIVE".equals(tblPackage.getModel().getValueAt(row, 3).toString()))
              {
                     comp.setForeground(Color.GREEN);
              }
              return comp;

        }
     } ;