简体   繁体   English

如何更改JTable中第一个单元格的背景颜色?

[英]How change the background color of first cell in a JTable?

Is everything okay? 一切都好吗?

I have the following table in my java application. 我的Java应用程序中有下表。 By the status he makes the line a certain color, as I will show in the code below. 通过状态,他使线条变为某种颜色,如下面的代码所示。

What I want is that only the first column is colored, the others want to appear with the default color. 我想要的是只有第一列是彩色的,其他的则要以默认颜色显示。

public class PriorityCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
        boolean isSelected, boolean hasFocus, int row, int column) {
    super.getTableCellRendererComponent(
            table, value, isSelected, hasFocus, row, column);

    //if (Integer.valueOf(1).equals(table.getValueAt(row, 1)) && 0 == column)   && 9 < column)
    if (String.valueOf(1).equals(table.getValueAt(row, 0))) {
        setForeground(Color.BLUE);  // or background
    }
    if (String.valueOf(2).equals(table.getValueAt(row, 0))) {
        setForeground(Color.GREEN);  // or background
    }
    if (String.valueOf(3).equals(table.getValueAt(row, 0))) {
        setForeground(Color.YELLOW);  // or background
    }
    if (String.valueOf(4).equals(table.getValueAt(row, 0))) {
        setForeground(Color.RED);  // or background
    }
    return this;
} 
}

在此处输入图片说明

Realized my question? 意识到我的问题了吗?

Does anyone can help me please? 有人可以帮我吗?

Thank you very much. 非常感谢你。

  1. Set custom renderer for target column: 为目标列设置自定义渲染器:

     table.getColumnModel().getColumn(COLUMN_INDEX).setCellRenderer(new PriorityCellRenderer()); 
  2. in getTableCellRendererComponent() validate column index if(column == COLUMN_INDEX) getTableCellRendererComponent()验证列索引if(column == COLUMN_INDEX)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM