How to center in JTable cell a value?

Daniel Pereira picture Daniel Pereira · Sep 15, 2011 · Viewed 82.2k times · Source

How to center a value in JTable cell? I'm using Netbeans.

Answer

camickr picture camickr · Sep 15, 2011

You need to customize the renderer. To center the first column you can do:

DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment( JLabel.CENTER );
table.getColumnModel().getColumn(0).setCellRenderer( centerRenderer );

To center all columns with String data you can do:

DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment( JLabel.CENTER );
table.setDefaultRenderer(String.class, centerRenderer);