代码之家  ›  专栏  ›  技术社区  ›  John R Doner

Java JTable TableCellRenderer问题

  •  0
  • John R Doner  · 技术社区  · 16 年前

    我已经在一个程序中实现了一个名为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...
    

    但当它运行时,它会将所有文本设置为绿色。是每次写入第9列中的单元格时都调用呈现程序,还是协议是什么?

    提前谢谢你的帮助。

    1 回复  |  直到 16 年前
        1
  •  0
  •   brian_d    16 年前

    因为您只想修改一列,所以请调整代码以指定列和行

        if (row == nmbrStocks && column == the_desired_column_you_wish_to_change)
        {
          if (up){
            cell.setForeground(Color.green);
          }else{
            cell.setForeground(Color.red);
          }
        }