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

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

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

例如:

新的 CustomTableCellRenderer(int 行,int 列);

这可能吗?

谢谢大家...

最佳答案

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

另外,这是关键,不要在渲染器的构造函数中设置 amount - 这是行不通的。相反,您必须在 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
    }

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

关于java - 如何更改 JTable (JAVA) 中特定单元格的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27215585/

相关文章:

java - IntelliJ Maven JAR "No main manifest attribute error"

java - Swing - 使用 JTextfield 输入创建 GridLayout

java - 绘制不同形状java时JColorChooser颜色出现问题

eclipse - 如何在Eclipse的代码辅助弹出窗口中更改当前选定行的颜色?

java - 基于 JComboBox 选择打开新框架

css - 如何通过 CSS 更改 Dygraph 系列的颜色

java - 使用 JPA 事务处理 Spring 批处理错误

java - 打印数组中的元素,元素之间用逗号分隔

java - 我的 Java 代码有什么问题,因为它一直使用默认答案进行回答?

用于过滤 jtable 行的 Java swing 切换按钮