Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align the values of the cells in JTable?

Tags:

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

like image 455
Venkat Avatar asked Mar 09 '10 11:03

Venkat


People also ask

How do I get the value of a JTable cell?

To get the value from a particular grid cell, you can use the wValue property of the JTable object. The property has the Row and Column parameters which specify the row and the column that contain the cell.

How can you change the appearance of data in cells in JTable?

We can change the background and foreground color for each column of a JTable by customizing the DefaultTableCellRenderer class and it has only one method getTableCellRendererComponent() to implement it.

What is JTable TableModel?

The TableModel interface specifies the methods the JTable will use to interrogate a tabular data model. The JTable can be set up to display any data model which implements the TableModel interface with a couple of lines of code: TableModel myData = new MyTableModel(); JTable table = new JTable(myData);

What is JTable in swing?

The JTable class is a part of Java Swing Package and is generally used to display or edit two-dimensional data that is having both rows and columns. It is similar to a spreadsheet. This arranges data in a tabular form.


1 Answers

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.

like image 75
camickr Avatar answered Oct 09 '22 21:10

camickr