0

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.

Amarnath
  • 8,736
  • 10
  • 54
  • 81
  • 1
    Note that `String.length` returns the number of characters in a `String`, while `setPreferredWidth` probably is expressed in pixels (not really mentioned in the javadoc, but this is the most likely scenario) – Robin Nov 05 '12 at 14:31

4 Answers4

6

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.

3

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).

Dan D.
  • 32,246
  • 5
  • 63
  • 79
  • +1 Thank you. Can you please tell me how to convert my string length to the pixel size and set it to the table column width – Amarnath Nov 05 '12 at 14:41
2

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.

Robin
  • 36,233
  • 5
  • 47
  • 99
2
Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319