Align the values of the cells in JTable?

Venkat picture Venkat · Mar 9, 2010 · Viewed 69.7k times · Source

I'm not aware of how to align the values of cells in JTable.

For Ex,The Jtable shows, Name Salary Mr.X 100000.50 XXXX 234.34 YYYy 1205.50

I want to align the "Salaries" in the following format.

   Name      Salary
   Mr.X      100000.50
   XXXX         234.34
   YYYy        1205.50

How to align as above the JTable

Answer

camickr picture camickr · Mar 9, 2010

There is no need to create a custom class for this, just use the default renderer:

DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
rightRenderer.setHorizontalAlignment(SwingConstants.RIGHT);
table.getColumnModel().getColumn(???).setCellRenderer(rightRenderer);

Or a better approach is to actually store Double values in the table and then a proper numeric renderer will be used and number renderers are automatically right aligned. You can then customize the formatting of the number using a Table Format Renderer.