Reputation: 8855
I am trying to set column width to the length of the column name. My problem is, I am not able to set it. When I use the following code the table is becoming like this,
tableA.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
for(int i = 0; i < tableA.getColumnCount(); i++) {
int columnLength = (modelA.getColumnName(i)).length();
tableA.getColumnModel().getColumn(i).setPreferredWidth(columnLength);
// tableA.getColumnModel().getColumn(i).setMinWidth(columnLength);
// tableA.getColumnModel().getColumn(i).setMaxWidth(columnLength);
}
I am getting the column length correctly from my table model.
When I use the above code the table is getting packed like this,
I am not able to understand where I am doing wrong.
Upvotes: 0
Views: 4542
Reputation:
As Dan has pointed out, you need to calculate the actual width of the column name based on the Font that is being used.
Something like:
String name = modelA.getColumnName(i);
Font f = tableA.getFont();
FontMetrics fm = tableA.getFontMetrics(f);
int width = fm.stringWidth(name);
tableA.getColumnModel().getColumn(i).setPreferredWidth(width);
Note that this is an extremely abbreviated example.
If you want to get it completely correct, you will need to query each column's renderer for the Font and the FontMetrics in order to get the correct values.
If all your renderers use the same font as the JTable, then this should be OK.
Upvotes: 6
Reputation: 109815
columnLength
== number or columns from ColumnModel
,
standard size is 80pixels
minimum columns size is at 10pixels
Upvotes: 2
Reputation: 36601
If you do not mind using SwingX, you can use the TableColumnExt#setPrototypeValue
method which allows you to set a 'prototype' value which will be used to determine the column width.
Upvotes: 2
Reputation: 32391
The setPreferredWidth
expects a value in pixels while the length of the column name is the length of a String
(number of characters in a String
).
Upvotes: 3