Java JTable Alternate Row Color not working

Iqbal Hossain picture Iqbal Hossain · Jul 20, 2013 · Viewed 15.1k times · Source

Why this following code not working? where is the problem? My jTable is initiated as jTable1;

jTable1.setDefaultRenderer(Object.class,new TableCellRenderer(){

            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                Component c = (Component) table.getCellRenderer(row, column);
                c.setBackground(row%2==0 ? Color.white : Color.yellow);                        
                return c;
            };

        });

Answer

bbhar picture bbhar · Oct 26, 2014

Recently while going through the source code of javax.swing.table.DefaultTableCellRenderer, I found following simple solution which will provide alternate row coloring for all tables in an application.

In the code, just after setting default look and feel insert following code:

UIDefaults defaults = UIManager.getLookAndFeelDefaults();
if (defaults.get("Table.alternateRowColor") == null)
    defaults.put("Table.alternateRowColor", new Color(240, 240, 240));