Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java JTable Alternate Row Color not working

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;
            };

        });
like image 985
Iqbal Hossain Avatar asked Dec 06 '25 04:12

Iqbal Hossain


2 Answers

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));
like image 186
bbhar Avatar answered Dec 07 '25 19:12

bbhar


  • override prepareRenderer for decorating whole row

  • for example based on Table Row Rendering by @camickr

like image 42
mKorbel Avatar answered Dec 07 '25 20:12

mKorbel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!