JTable,自定义标题渲染器和排序图标

时间:2011-10-17 10:43:11

标签: swing header jtable renderer

在JTable标头上设置自定义渲染器时,我得到了预期的可视行为(边框,字体,对齐方式......)但我无法获得通常在排序行时出现的LaF排序图标。

这是设置自定义标题渲染器的代码:

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

这是自定义标题渲染器的摘录:

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

任何提示?

1 个答案:

答案 0 :(得分:12)

尝试委托L&amp; F安装的渲染器:

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()));

正如kleopatra警告的那样,这可能不是最稳定的解决方案,请参阅我刚刚投入生产的this bug report。该问题的记者建议使用自定义的Table / TableColumn子类来更新TableColumn#getDefaultRenderer中的委托渲染器。