Search code examples
javaswingjtablejtableheader

Creating a JTable with alternating row colors


enter image description here

I am pretty new to java swing and i just started working on JTable. I want to create a JTable Which look like the above image? Can anybody help me beacause i am not so familiar with JTable?


Solution

  • Overriding the prepareRender(...) method of the JTable allows you to customize rendering for the entire row without providing custom renderers.

    The basic logic would be something like:

    JTable table = new JTable( model )
    {
        public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
        {
            Component c = super.prepareRenderer(renderer, row, column);
    
            //  Alternate row color
    
            if (!isRowSelected(row))
                c.setBackground(row % 2 == 0 ? getBackground() : Color.LIGHT_GRAY);
    
            return c;
        }
    };
    

    Check out Table Row Rendering for more information and working examples.