I have a JavaFX 2 table that is displaying contact details for people, lets imagine there are three columns: first name, last name and email address. When my application starts it populates the table with several rows of data about the people already in the system.
The problem is that the column widths are all the same. Most of the time the first and last name is displayed in full but the email address is getting clipped. The user can double click the divider in the header to resize the column but that will become tedious quickly.
Once the table has been pre-populated I would like to programatically resize all the columns to display the data they contain but I can't figure out how to achieve this. I can see that I can call col.setPrefWidth(x)
but that doesn't really help as I would have to guess the width.
This works for me in JavaFX 8
In the other examples you have the problem, the vertical scrollbar width is ignored.
If you had 4 columns and only last column needed to expand to fill the rest of the table width and the other columns remained the size I set in Scene Builder.
Or if you had 2 columns that needed to expand then.
You can also do it by editing the fxml file if you have one.
The parameter
prefWidth
allows you to modify the default with of a column.To generelize the width and use any number and make sure that the width is 100% of the table's width, you can use :
If your total number of columns are pre-known. You can distribute the column widths among the tableview's width:
In this code, the width proportions of columns are kept in sync when the tableview is resized, so you don't need to do it manually. Also the
surnameCol
takes the half space of the tableview's width.As I use SceneBuider, I just define the MinWidth, and MaxWidth to some columns and to the main column I just define the PrefWidth to "USE_COMPUTED_SIZE"