views:

471

answers:

3

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

A: 

The way to go about it is to specify a custom cell renderer for each column. Each renderer will format that data differently (names will e aligned to the left, decimals to the right, ...)

Itay
+2  A: 

From this forum post:

Create a class that extends DefaultTableCellRenderer and implement the getTableCellRendererComponent() method, something like:

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
    JLabel renderedLabel = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    renderedLabel.setHorizontalAlignment(SwingConstant s.RIGHT);
    return renderedLabel;
}

and install this renderer for the column in question.

Now you only need to make sure that each value has the same number of decimal places because for most fonts, all digits have the same width.

Aaron Digulla
+1  A: 

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

DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
rightRenderer.setHorizontalAlignment( JLabel.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.

camickr