Change the color of a row in a jTable

北城余情 提交于 2019-12-12 01:13:24

问题


I have a jTable as following :

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.

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é :

this is my cell rendering :

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());
        }
    }

回答1:


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.



来源:https://stackoverflow.com/questions/16893333/change-the-color-of-a-row-in-a-jtable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!