JTable Right Align Header

前端 未结 13 2338
太阳男子
太阳男子 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:46

    I have created a class based on the solution of pvbemmelen62, that can be used very easily, for example:

    AlignHeaderRenderer.install(myTable, new int[] { SwingConstants.RIGHT,
                            SwingConstants.RIGHT, SwingConstants.LEFT });
    

    or

    AlignHeaderRenderer.install(myTable, 0, SwingConstants.RIGHT);
    AlignHeaderRenderer.install(myTable, 1, SwingConstants.RIGHT);
    

    Here's the code:

    public class AlignHeaderRenderer implements TableCellRenderer {
    
    private final TableCellRenderer renderer;
    private final int alignment;
    
    public static void install(final JTable table, final int[] alignments) {
        for (int i = 0; i < alignments.length; ++i)
            install(table, i, alignments[i]);
    }
    
    public static void install(final JTable table, final int row,
            final int alignment) {
        table.getTableHeader().getColumnModel().getColumn(row)
                .setHeaderRenderer(new AlignHeaderRenderer(table, alignment));
    }
    
    private AlignHeaderRenderer(final JTable table, final int alignment) {
        renderer = table.getTableHeader().getDefaultRenderer();
        this.alignment = alignment;
    }
    
    @Override
    public Component getTableCellRendererComponent(final JTable table,
            final Object value, final boolean isSelected,
            final boolean hasFocus, final int row, final int col) {
        final Component c = renderer.getTableCellRendererComponent(table,
                value, isSelected, hasFocus, row, col);
        ((JLabel) c).setHorizontalAlignment(alignment);
        return c;
    }
    
    }
    
    0 讨论(0)
提交回复
热议问题