我有一个四列的JTable。我试图居中对齐那些列之一的标题。我有一个可行的解决方案,但问题是标题的默认呈现/样式似乎丢失了。查看截图。我想获取当前的TableCellRenderer,将标题对齐方式更改为CENTER,并将适应的TableCellRenderer应用到特定列。我怎样才能做到这一点?

表格截图

java - 如何在不丢失默认渲染的情况下修改TableCellRenderer?-LMLPHP

我的JTable类

public class MyTable extends JTable {

public MyTable() {
    String[] headers = { "Parent", "Summary", "Key", "Processed" };
    MyTableModel model = new MyTableModel(headers);

    Object[] testrow = { "TST-99999", "S", "K", false };
    model.addRow(testrow);

    setModel(model);

    Enumeration<TableColumn> columns = getColumnModel().getColumns();
    while (columns.hasMoreElements()) {
        TableColumn column = (TableColumn) columns.nextElement();
        System.out.println(column.getHeaderValue());
        column.setResizable(false);
        switch ((String) column.getHeaderValue()) {
        //case "Parent":
        //case "Key":
        case "Processed":
            column.setMaxWidth(80);
            column.setMinWidth(80);
            column.setHeaderRenderer(new CenterRenderer());
            break;
        }
    }
}
}


我的TableModel类

public class MyTableModel extends DefaultTableModel {

public MyTableModel(String[] headers) {
    for(String header:headers){
        addColumn(header);
    }
}

@Override
public boolean isCellEditable(int row, int column) {
   return false;
}


@Override
public Class<?> getColumnClass(int index) {
    switch (index) {
    case 0:
        return String.class;
    case 1:
        return String.class;
    case 2:
        return String.class;
    case 3:
        return Boolean.class;
    default:
        return String.class;
    }

}


}

我的TableCellRenderer类

public class CenterRenderer extends DefaultTableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    label.setHorizontalAlignment(SwingConstants.CENTER);
    return label;
}
}

最佳答案

而不是扩展DefaultTableCellRenderer,而是委托给JTableHeader的默认渲染器:

public class CenterRenderer implements TableCellRenderer {
    private final JTableHeader header;

    public CenterRenderer(JTableHeader header) {
        this.header = header;
    }

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        JLabel label = (JLabel) header.getDefaultRenderer().getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        label.setHorizontalAlignment(SwingConstants.CENTER);
        return label;
    }
}

10-05 18:00