0

Trying to make my JTable column width to be auto resized to it's value width.

for example i have a column1 with text "just a test" and i get this result :

|column1|
|-------|
|just ..|

but i need it to be like so:

|column1    |
|-----------|
|just a test|

I've already searched whole JTable library for this one, can't find anything related. Any help?

Ervinas34
  • 133
  • 10

1 Answers1

1

First answer

To do this you should access the column of the table as this:

TableColumn column = null; column = table.getColumnModel().getColumn(/*here the index of your column*/); column.sizeWidthToFit();

be careful if header is empty or it will do nothing

some of the sources just in case https://docs.oracle.com/javase/tutorial/uiswing/components/table.html#width https://docs.oracle.com/javase/7/docs/api/javax/swing/table/TableColumn.html#sizeWidthToFit()

Update

after some more search I found this previous post that should be a better answer to your problem Auto resizing the JTable column widths

  • The problem is, that the method `sizeWidthToFit` only resize column to fit the width of column header, but not the values. – Sergiy Medvynskyy Sep 04 '17 at 08:36
  • Yes, i need to fit values and column names. – Ervinas34 Sep 04 '17 at 08:43
  • ok, some updates to my initial answer hope this be more accurate – Jorge Hernandez Sep 04 '17 at 09:05
  • @JorgeHernandez this is kinda working, thanks. Got other problem. Column value is being showed, but if the string is long, still do not show all, and if they value is shorter than COLUMN NAME in header, the header shorterers. Any ideas? – Ervinas34 Sep 04 '17 at 10:15
  • @Ervinas34, `if they value is shorter than COLUMN NAME in header, the header shorterers.` - see this posting: https://stackoverflow.com/a/31977776/131872 – camickr Sep 04 '17 at 14:51