How to align the column title of a JTable?

3

I have an (abstract table model) table and would like to center the column headings.

I've tried the following:

DefaultTableCellRenderer centralizado = new DefaultTableCellRenderer();        
centralizado.setHorizontalAlignment(SwingConstants.CENTER);
tabela.getColumnModel().getColumn(0).setCellRenderer(centralizado);

What's wrong? Can not do just this way?

    
asked by anonymous 30.10.2016 / 22:40

1 answer

5

The code presented will only set the rendering of the cells of the column, the header is rendered separately.

To center the title of the columns you must pass the renderer to the JTableHeader of the table, which is responsible for rendering the header:

JTableHeader header =  jTable1.getTableHeader();
DefaultTableCellRenderer centralizado = (DefaultTableCellRenderer) header.getDefaultRenderer();
centralizado.setHorizontalAlignment(SwingConstants.CENTER);

Or in a one-line call:

((DefaultTableCellRenderer) jTable1.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(SwingConstants.CENTER);
    
31.10.2016 / 00:27