开发者

How to invoke DefaulCelleRenderer from a CustomCellRenderer for a specific JTable cell

开发者 https://www.devze.com 2023-01-03 12:44 出处:网络
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 ha

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.


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;
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消