如何更改 JTable (JAVA) 中特定单元格的颜色



好吧,我的问题是如何在Java中更改JTable中特定单元格的颜色? 据我所知,我应该做的第一件事是覆盖CellRenderd的方法,我已经做了这部分,如下所示:

public class CustomTableCellRenderer extends DefaultTableCellRenderer 
{
    int amount;
    int f,c;
    public CustomTableCellRenderer(int a)
    {
        amount = a;

    }
    public CustomTableCellRenderer()
    {


    }
@Override
public Component getTableCellRendererComponent
   (JTable table, Object value, boolean isSelected,
   boolean hasFocus, int row, int column) 
   {
    Component cell = super.getTableCellRendererComponent
    (table, value, isSelected, hasFocus, row, column);
    if(amount == 3)
    {
            cell.setBackground(Color.LIGHT_GRAY);
    }
    if(amount == 1)
    {
        cell.setBackground(Color.cyan);
    }
    if(amount == 2)
    {
        cell.setBackground(Color.orange);
    }

    return cell;
 }

}

当我想更改单元格的颜色时,我更改了颜色,但它会更改整个列,我使用覆盖的代码部分如下所示:

 Cache_table.getColumnModel().getColumn(columna).setCellRenderer(new    CustomTableCellRenderer(1));

如何指定要更改颜色的单元格的确切位置,指定行数和列数:

例如:

new CustomTableCellRenderer(int row, int column);

这可能吗?

谢谢大家

考虑使用 else if 语句,然后在默认的最后一个 else 块中添加默认值。

另外,这是关键,不要在渲染器的构造函数中设置数量 - 这是行不通的。相反,您必须在 getTableCellRendererComponent 方法中获取金额结果,通常从单元格的值或同一行上另一个模型单元格的值获取。

@Override
public Component getTableCellRendererComponent
   (JTable table, Object value, boolean isSelected,
   boolean hasFocus, int row, int column) {
    Component cell = super.getTableCellRendererCo
    // check that we're in the right column
    if (column != correctColumn) { 
        // if not the right column, don't change cell
        return cell;       
    }
    // SomeType is the type of object held in the correct column
    SomeType someType = (SomeType) value;
    if (value == null) {
        value = "";
        return cell;       
    }
    // and hopefully it has a method for getting the amount of interest
    int amount = someType.getAmount();
    if(amount == 3) {
            cell.setBackground(Color.LIGHT_GRAY);
    } else if(amount == 1) {
        cell.setBackground(Color.cyan);
    } else if(amount == 2) {
        cell.setBackground(Color.orange);
    } else {
        cell.setBackground(null); // or a default background color
    }

此外,您可能需要确保您的单元格是不透明的。

最新更新