Does anyone know how to align text in JTable?
i am retrieving information from the db. and populating them in a JTable.
Printable View
Does anyone know how to align text in JTable?
i am retrieving information from the db. and populating them in a JTable.
It depends on the TableCellRenderer used to render the cell contents to the display. The default table cell renderer, verbosely called DefaultTableCellRenderer (you get this if you don't specify one), is a subclass of JLabel, so you can call the alignment methods of JLabel on it, something like this:DefaultTableCellRenderer dtcr = (DefaultTableCellRenderer)myTable.getColumn("Widgets").getCellRenderer();
dtcr.setHorizontalTextPosition(SwingConstants.CENTER);
Dave
To email me remove '_spamjam' from my email address
hi,
when i try implementing the way you suggest, i am getting a null ptr exception. i think the cell renderer is not getting the correct value. in getcolumn method of the cell renderer is "Widgets" the name of the column?
I put in "Widgets" as an example column name. In a default situation, if an identifier is not set for a TableColumn, the identifier is the column header text. If you have set an identifier for the column, you should use that. The point is just to get the TableColumn you're after... if you don't want to do it this way, you can get the column from the TableColumnModel by its index:TableColumn col2 = myTable.getColumnModel().getColumn(2);
You'll find all this in the JavaDoc for JTable. It pays to browse this stuff.
Dave
To email me remove '_spamjam' from my email address
DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();
dtcr.setHorizontalAlignment(SwingConstants.RIGHT);
table.getColumn("ABC").setCellRenderer(dtcr);
table.getColumn("def").setCellRenderer(dtcr);
table.getColumn("ghi").setCellRenderer(dtcr);
......
Congratulations on answering a 9 year old question which had already been answered :rolleyes:
Please do not revive old threads.