JTable Right Align Header

前端 未结 13 2528
太阳男子
太阳男子 2020-11-27 19:03

Basically, I have a JTable containing columns with right-aligned cells but left-aligned headers which looks really bad. I would like to right-align the headers of these colu

13条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 19:21

    The secret is to use the renderer from a dummy table to get correct L&F, and copy the alignment from the real table's row renderer. That way each column in aligned separately. Here is the code:

    table.getTableHeader().setDefaultRenderer(new DefaultTableCellRenderer() {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
            Component c2 = dummy.getTableHeader().getDefaultRenderer().getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
            if (table.getRowCount() > 0) {
                Component c3 = table.getCellRenderer(0, col).getTableCellRendererComponent(table, value, isSelected, hasFocus, 0, col);
                if (c2 instanceof JLabel && c3 instanceof JLabel)
                    ((JLabel)c2).setHorizontalAlignment(((JLabel)c3).getHorizontalAlignment());
            }
            return c2;
        }
        private final JTable dummy = new JTable();
    });
    

    The above code does not keep any references to renderers, so it avoids the NPE bug mentioned above. It does not require any named class, so you can just drop the code in wherever you need it.

提交回复
热议问题