Search code examples
javaswingjtablewindow-resizetablecellrenderer

How to keep JTable custom renderer looks on window resize?


I have a JTable inside my Java application and applied to it there is a custom renderer that changes the background color of the last row of the table. Like this:

enter image description here

I achieve that with the following code for the custom renderer:

table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer(){
    @Override
    public Component getTableCellRendererComponent(JTable table,
            Object value, boolean isSelected, boolean hasFocus, int row, int col) {
                
        super.getTableCellRendererComponent(table, value, isSelected,
                                            hasFocus, row, col);
                
        String status = (String)table.getModel().getValueAt(row, 0);
        if ("Total".equals(status)) {
            setBackground(Color.GRAY);
            setForeground(Color.WHITE);
        } 
                
        this.setHorizontalAlignment(CENTER);
        return this;
    }
});

However, when I resize the window, it looks like this:

enter image description here

To get it back to normal I have to clear the table and add the items again, what should I do in order to keep the table look when resizing? Thank you.


Solution

  • You forgot the else block to set the colors back:

    if ("Total".equals(status)) {
        setBackground(Color.GRAY);
        setForeground(Color.WHITE);
    } else {
        // set colors back to the default settings
        setBackground(null);
        setForeground(null);
    }
    

    Otherwise the renderer remains "set" and will color all cells gray/white. Think of a renderer like a rubber stamp that is used to stamp out a lot of the same thing. If you change it's colors and don't change them back, the stamp is "stuck" in color mode.