如何在JTable中更改行的颜色 [英] How to change color of row in JTable

查看:138
本文介绍了如何在JTable中更改行的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改JTable中整行的颜色.

I want to change color of whole row in my JTable.

我定义了JTable:

I defined the JTable:

JTable table = new JTable(data, columnNames);

其中数据,columnNames是字符串表.

where data, columnNames are the String tables.

最常见的方法是编写自己的类:

The most common way to do this is to write own class:

public class StatusColumnCellRenderer extends DefaultTableCellRenderer {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {

            //Cells are by default rendered as a JLabel.
            JLabel l = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);

            //Get the status for the current row.

            l.setBackground(Color.GREEN);

            //Return the JLabel which renders the cell.
            return l;
        }
    }

并致电:

this.table.getColumnModel().getColumn(0).setCellRenderer(new StatusColumnCellRenderer());

但这是行不通的.我在做什么错了?

But it is doesn't work. What am I doing wrong?

推荐答案

您最初正确设置了TableCellRenderer,但随后将其替换为以下代码:

You're setting the TableCellRenderer correctly initially but then you're replacing it with this code:

for (int i = 0 ; i < table.getColumnCount(); i++)
   table.getColumnModel().getColumn(i).setCellRenderer( centerRenderer );

对其进行更改,以使其将彩色单元格渲染器设置为正确的索引(并添加大括号(!)):

Change it so that it sets the colored cell renderer at the correct index (and add braces(!)):

for (int i = 0; i < table.getColumnCount(); i++) {
    TableColumn column = table.getColumnModel().getColumn(i);
    if (i == COLOR_COLUMN) { // COLOR_COLUMN = 1
        column.setCellRenderer(new StatusColumnCellRenderer());
    } else { 
        column.setCellRenderer(centerRenderer);
    }
}

这篇关于如何在JTable中更改行的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆