Search code examples
javaswingcolorsjtabletablecellrenderer

Cellrenderer change cell background color also change value format, alignment


I use cellRenderer to change my cells (columns) backgroud color but it also make change the cell value format as LEFT columns on image, i'd keep the default format as the RIGHT column on image, here my simple code:

DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setBackground(Color.ORANGE);
mytable.getColumnModel().getColumn(3).setCellRenderer( centerRenderer );

Thank you so much here is the image as description above

enter image description here


Solution

  • You want to create a custom renderer that will allow you to format the data.

    The basic logic would be something like:

    public class IntegerRenderer extends DefaultTableCellRenderer
    {
        private Format formatter = new NumberFormage.getIntegerInstance();
    
        public IntegerRenderer()
        {
            setHorizontalAlignment( SwingConstants.RIGHT );
        }
    
        public void setValue(Object value)
        {
            //  Format the Object before setting its value in the renderer
    
            try
            {
                if (value != null)
                    value = formatter.format(value);
            }
            catch(IllegalArgumentException e) {}
    
            super.setValue(value);
        }
    }
    

    Then you just set the background color of the renderer.

    Check out Table Format Renderers for reusable classes that make is easy to create custom renders for numbers, percentages, dates etc.