tags:

views:

27

answers:

1

Hi All,

I have a class that has a Boolean field in it. I display in a JTable a list of of those classes. I created a CustomCellRenderer to change the background color of the rows, so I could have different colors.

the problem: when the customrenderer is applied on the Boolean field, (true/false) is rendered instead of the default renderer's checkbox.

how can I have both features: background colors and checkbox?

here is the customrenderer code:

public class CustomCellRenderer 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);

        if (isSelected) {
            cell.setBackground(Color.red);
        } else {
            if (row % 2 == 0) {
                cell.setBackground(new Color(110,134,214));

            } else {
                cell.setBackground(Color.lightGray);

            }
        }
        return cell;
    }
}

thanks in advance for any help.

A: 

Hi, I got it.

I found this :

add a check box to only one cell in a JTable

I used the BooleanRenderer that I called from the getTableCellRendererComponent method of the CustomCellRenderer.

I just added a line in this method the delegate the rendering:

public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int column) {
        //delegate if boolean
        if(value instanceof Boolean) return booleanRenderer.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
        if (isSelected) {
            setBackground(selectedColor);
            setForeground(unSelectedColorWhite);
        } else {
            if (row % 2 == 0) {
                setBackground(unSelectedColorBlue);
            } else {
                setBackground(unSelectedColorWhite);
            }
            setForeground(selectedColor);
        }
        setText(" " + table.getValueAt(row, column)); 
        selected = isSelected;

        return this;
    }
albert green