更改jTable中行的颜色 [英] Change the color of a row in a jTable

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

问题描述

我有一个jTable,如下所示:

I have a jTable as following :

我希望当Quantité中的值小于Min seuil de suantité中的值时,将行的颜色更改为粉红色.

I want when the value in the Quantité is less than the value in the Min seuil de suantité, to change the color of the row to pink.

在程序的加载中一切正常,但是当我执行某些事件(例如单击表)时,即使Quantité的值不小于的值,所有行的颜色也会更改. Min seuil de quantité:

In the load of the program all works fine, but when I do some event like click on the table, the color of all the rows is changed even if the the value of the Quantité is not less than the value of the Min seuil de quantité :

这是我的单元格渲染:

public class CustomTableCellRenderer extends DefaultTableCellRenderer {
    public Component getTableCellRendererComponent(JTable table,
            Object obj, boolean isSelected, boolean hasFocus, int row, int column) {
        Component cell = super.getTableCellRendererComponent(
                table, obj, isSelected, hasFocus, row, column);

        setHorizontalAlignment(SwingConstants.LEFT);

        int selectedRow = table.convertRowIndexToModel(row);
        if (table.getModel().getValueAt(selectedRow, 3) != null && table.getModel().getValueAt(selectedRow, 4) != null) {
            int quantite = Integer.parseInt(table.getModel().getValueAt(selectedRow, 3).toString());
            int minQuantite = Integer.parseInt(table.getModel().getValueAt(selectedRow, 4).toString());
            if (quantite < minQuantite) {
                if (isSelected) {
                    cell.setBackground(new Color(255, 138, 239));
                } else {
                    cell.setBackground(new Color(252, 189, 252));
                }
            }
        }
        return cell;
    }
}

这是使我能够影响到表格的单元格渲染的代码:

and this is the code which allows me to affect the cell rendering to my table :

private void cellRendering(){
        for (int i = 0; i < masterTable.getColumnCount(); i++) {
            tcol = masterTable.getColumnModel().getColumn(i);
            tcol.setCellRenderer(new CustomTableCellRenderer());
        }
    }

推荐答案

此处找到更多详细信息.

The renderer is a rubber stamp that remembers what ink was applied last. Be sure to set the desired color each time the renderer is invoked. More details can be found here.

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

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