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 sta
If your total number of columns are pre-known. You can distribute the column widths among the tableview's width:
nameCol.prefWidthProperty().bind(personTable.widthProperty().divide(4)); // w * 1/4
surnameCol.prefWidthProperty().bind(personTable.widthProperty().divide(2)); // w * 1/2
emailCol.prefWidthProperty().bind(personTable.widthProperty().divide(4)); // w * 1/4
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.
Also, a very simple trick based on an AnchorPane
will be a good solution.
We gonna wrap the TableView
into a AnchorPane
but also we gonna anchor the left and right side of the TableView
like this:
AnchorPane wrapper = new AnchorPane();
AnchorPane.setRightAnchor(table, 10.0);
AnchorPane.setLeftAnchor(table, 10.0);
wrapper.getChildren().add(table);
This simple code will stretch the TableView
in both directions (right and left) also, it will adjust whenever the scrollbar is added.
You can get an idea of how this works watching this animated gif.
Now you can resize the columns, adding these lines:
fnColumn.setMaxWidth( 1f * Integer.MAX_VALUE * 30 ); // 30% width
lnColumn.setMaxWidth( 1f * Integer.MAX_VALUE * 40 ); // 40% width
emColumn.setMaxWidth( 1f * Integer.MAX_VALUE * 30 ); // 30% width