Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JTable, custom header renderer and sorting icons

While setting a custom renderer on a JTable header I get the expected visual behavior (borders, font, alignment, ...) but I can't manage to get the LaF sorting icons that usually appear when the rows are sorted.

This is the code for setting the custom header renderer:

Enumeration<TableColumn> columns = getColumnModel().getColumns();
   while (columns.hasMoreElements())
   columns.nextElement().setHeaderRenderer(new XDeliveryTableHeaderRenderer());

This is an excerpt of the custom header renderer:

public class MyTableHeaderRenderer extends JLabel implements TableCellRenderer {
     private static final Font labelFont = new Font("Arial", Font.BOLD, 11);

     @Override
     public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        setFont(labelFont);
        setHorizontalAlignment(SwingConstants.CENTER);
        setText(value.toString());
        setBorder(BorderFactory.createEtchedBorder());
        return this;
     }
}

Any hints?

like image 955
S3lvatico Avatar asked Feb 03 '23 12:02

S3lvatico


1 Answers

Try delegating to the L&F installed renderer:

public class MyTableHeaderRenderer implements TableCellRenderer {
 private static final Font labelFont = new Font("Arial", Font.BOLD, 11);

 private TableCellRenderer delegate;

 public MyTableHeaderRenderer(TableCellRenderer delegate) {
     this.delegate = delegate;
 } 

 @Override
 public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {

    Component c = delegate.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

    if(c instanceof JLabel) {
        JLabel label = (JLabel) c;
        label.setFont(labelFont);
        label.setHorizontalAlignment(SwingConstants.CENTER);
        label.setBorder(BorderFactory.createEtchedBorder());
    }
    return c;
 }
}

// Usage:
JTableHeader header = table.getTableHeader();
header.setDefaultRenderer(new MyTableHeaderRenderer(header.getDefaultRenderer()));

As kleopatra warned, this might not be the most stable solution, see this bug report which I just got in production. The reporter of that issue suggest using a custom Table/TableColumn sub classes which updating the delegate renderer in TableColumn#getDefaultRenderer.

like image 77
Walter Laan Avatar answered Feb 05 '23 01:02

Walter Laan