Custom TableCellRenderer/TreeTableCellRenderer doesn't render Table cells

4.2k views Asked by At

I made this CustomCellRenderer class intended to be used in JXTreeTable and JXTable objects since I have many of these in my project. So this class implements TreeCellRenderer and TableCellRenderer interfaces:

public class CustomCellRenderer extends JLabel 
                                implements TreeCellRenderer, TableCellRenderer {

    @Override
    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
        setBackground(selected ? new Color(83,142,213) : Color.white);
        setForeground(selected ? Color.white : Color.black);
        //here is the icon setting code but it's irrelevant to my problem
        setText(value != null ? value.toString() : "<null>");
        return this;
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        setBackground(isSelected ? new Color(83,142,213) : Color.white);
        setForeground(isSelected ? Color.white : Color.black);
        setText(value != null ? value.toString() : "<null>");
        return this;
    }
}

And here is the code where I set the renderer:

jXTreeTableConsumos.setDefaultRenderer(Object.class, new CustomCellRenderer());
jXTreeTableConsumos.setTreeCellRenderer(new CustomCellRenderer());

I'm expecting background and foreground become blue and white respectively when a row is selected. However it only happens at Tree table cell (first column) while only foreground changes and background stills white in the other cells in the very same selected row:

enter image description here

Could anybody please tell me why cells (that are not tree cells) don't change their background color?

1

There are 1 answers

1
dic19 On BEST ANSWER

Thanks everybody for your comments and suggestions. I found the solution in JComponent#setBackground(Color bg) documentation:

Sets the background color of this component. The background color is used only if the component is opaque, and only by subclasses of JComponent or ComponentUI implementations. Direct subclasses of JComponent must override paintComponent to honor this property.

Since my CustomCellRenderer extends from JLabel the only thing I have to do is make sure it's opaque and its background color will be painted:

@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    setOpaque(true);//adding this line I solved my problem
    setBackground(isSelected ? new Color(83,142,213) : Color.white);
    setForeground(isSelected ? Color.white : Color.black);
    setText(value != null ? value.toString() : "<null>");
    return this;
}

enter image description here