【问题标题】:Changing colour of specific cell in a JTable更改 JTable 中特定单元格的颜色
【发布时间】:2014-02-10 21:01:54
【问题描述】:

我正在尝试更改 JTable 中一列中一个或多个特定单元格的颜色。我在这里看到的答案都是指这种特殊的方法;

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
    Component y = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    y.setBackground(new Color(255,0,0));

    return y;
}

但问题是我不明白这是如何工作的,在我的其他课程中,我有一个字符串 Jtable,我想根据它们的字符串值更改某些单元格的颜色,但是我只找到了解决方案请允许我更改 jtable 中整列单元格的颜色,而不是特定单元格的颜色。

【问题讨论】:

  • 您的问题似乎有点为时过早。您需要学习如何使用 TableCellRenderer,例如扩展 DefaultTableCellRenderer 或 AbstractTableCellRenderer。如果您阅读 JTable tutorial 和相应的 API,并更加努力地搜索此站点,您会发现至少需要初步了解此站点的所有信息。

标签: java swing colors jtable cell


【解决方案1】:

我有一个字符串 Jtable,我想根据它们的字符串值更改某些单元格的颜色

所有单元格使用相同的渲染器,因此您每次都需要重置背景。

您将需要在自定义渲染器代码中使用 if 条件。比如:

if (!isSelected)
    if (value.equals(...))
        y.setBackground(new Color(255,0,0));
    else
        y.setBackground(table.getBackground())

【讨论】:

  • 好吧,吹毛求疵(并没有真正帮助 OP,因为她/他似乎需要退后一步,从更基本的东西开始 ;-):仅检查选定状态还不够好,可能有更多的状态需要区分(比如 dropLocation、focused && editable,...)。 A more complete solution - 偏向于我 - 是在 调用 super 之前检查自己的情况,如果不感兴趣,请将颜色设置为 null
【解决方案2】:

您可以使用 DefaultTableCellRenderer 为 JTable 中的备用行着色。

table.setDefaultRenderer(Object.class, new TableCellRenderer(){
    private DefaultTableCellRenderer DEFAULT_RENDERER =  new DefaultTableCellRenderer();

            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                Component c = DEFAULT_RENDERER.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                if(isSelected){
                    c.setBackground(Color.YELLOW);
                }else{
                if (row%2 == 0){
                    c.setBackground(Color.WHITE);

                }
                else {
                    c.setBackground(Color.LIGHT_GRAY);
                }     }

       //Add below code here
                return c;
            }

        });

如果您想使用特定行的值为您的行着色,那么您可以使用类似的东西。将这些行添加到上面

if(table.getColumnModel().getColumn(column).getIdentifier().equals("Status")){//Here `Status` is column name
    if(value.toString().equals("OK")){//Here `OK` is the value of row

        c.setBackground(Color.GREEN);
    }   
}

【讨论】:

    猜你喜欢
    • 2014-02-17
    • 1970-01-01
    • 2015-01-28
    • 2011-08-14
    • 2011-08-06
    • 2011-11-03
    • 2014-08-24
    • 2014-07-20
    • 2018-08-20
    相关资源
    最近更新 更多