开发者

JTable, custom header renderer and sorting icons

While setting a custom renderer on a JTable header I get the expected visual behavior (borders, font, alig开发者_StackOverflow中文版nment, ...) 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜