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

时间:2014-11-30 16:44:02

标签: java swing colors jtable tablecellrenderer

我的问题是如何在Java中改变JTable中特定单元格的颜色?据我所知,我应该做的第一件事就是覆盖方法CellRendered我已经按照以下方式做了这个部分:

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);

这可能吗?

谢谢你们,

1 个答案:

答案 0 :(得分:2)

考虑使用else if语句,然后在默认的last 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
    }

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