How to align the column title of a Jtable?

Asked

Viewed 1,310 times

4

I have a table (Abstract table model) and would like to center column titles.

I tried the following:

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

What is wrong? It is not possible to do just this way?

1 answer

6


The code displayed will only define the rendering of the column cells, the header is rendered the part.

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

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

Or on a call from a line:

((DefaultTableCellRenderer) jTable1.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(SwingConstants.CENTER);
  • 1

    @Gustavosantos this solution solved the problem?

  • 2

    solved perfectly !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.