Amarnath
Amarnath

Reputation: 8855

JTable set column width not working

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,

Set Column Width

I am not able to understand where I am doing wrong.

Upvotes: 0

Views: 4542

Answers (4)

user330315
user330315

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

mKorbel
mKorbel

Reputation: 109815

Upvotes: 2

Robin
Robin

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

Dan D.
Dan D.

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

Related Questions