Wednesday, July 28, 2010

Auto-Alignment of JXTable TableHeaders

As a followup of the previous post, here's example code to automatically align the headers of a JXTable with the data underneath, using the new fangled SwingX renderers.

import org.jdesktop.swingx.renderer.DefaultTableRenderer;

public class AutoAlignedHeaderRenderer extends DefaultTableRenderer {
  
  // constructors etc. omitted  ...

  @Override
  public Component getTableCellRendererComponent(JTable table, Object value, boolean selected, boolean focused, int row, int column) {
   
    TableCellRenderer dataRenderer = table.getCellRenderer(row, column);

    int align = SwingConstants.LEFT;  // default to left

    if (dataRenderer instanceof JLabel) { // backwards compatibility
      align = ((JLabel)dataRenderer).getHorizontalAlignment();
    }
    else if (dataRenderer instanceof AbstractRenderer) {
      AbstractRenderer ar = (AbstractRenderer)dataRenderer;      
      align = ar.getComponentProvider().getHorizontalAlignment();
    }
    
    componentController.setHorizontalAlignment(align);

    return super.getTableCellRendererComponent(table, value, selected, focused, row, column);

  }

}