9

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

有什么提示吗?

4

1 回答 1

12

尝试委托 L&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 警告的那样,这可能不是最稳定的解决方案,请参阅我刚刚在生产中得到的这个错误报告。该问题的报告者建议使用自定义 Table/TableColumn 子类来更新 TableColumn#getDefaultRenderer 中的委托渲染器。

于 2011-10-17T13:52:13.080 回答