Search code examples
javaswingjtablebackground-colortablecellrenderer

CellRenderer setBackground replaces Value in JTable


So I wanted to change the Color of the background of specific columns. Therefore I created a new class CellRenderer extends DefaultTableCellRenderer and I overwrote the method getTableCellRendererComponent. It works fine, the color changes when I start my Project, but my Problem is I added also a new Object[] to my JTable and now I can see only the color changed, not the Values in the cell.

How can I fix this?

My CellRenderer Class Method getTableCellRendererComponent

@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        
        if(column >= 4 && column <= 9) {
           this.setBackground(Color.decode("#5CACEE"));
        }else if (column > 9 && column <= 17) {
           this.setBackground(Color.decode("#B0E2FF"));
        }else {
            this.setBackground(Color.decode("#B0C4DE"));
        }
        
        return this;
    }

My constructor in my Main class where i set the CellRenderer to my JTable

dcr = new MyCellRenderer();
tblData.setDefaultRenderer(Object.class, dcr);

And the snippet where I add the Values to the Table

dtm.addRow(new Object[]{false,"yes","only",ow,"CCSITT3","PANDA_TF001","failed","PANDA","5718200303","1"});

And here you can see the GUI

enter image description here


Solution

  • Fixed it! Was referring to this. instead of the component

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                
                Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                
                if(column >= 4 && column <= 9) {
                   c.setBackground(Color.decode("#5CACEE"));
                }else if (column > 9 && column <= 17) {
                   c.setBackground(Color.decode("#B0E2FF"));
                }else {
                    c.setBackground(Color.decode("#B0C4DE"));
                }
                
                return c;
            }