TableView: column’s width using percentage in JavaFX
December 3, 2012 Leave a comment
In my previous post you’ve successfully learned how to simply use a TableView. It is obvious that a tables has columns and columns have a size. Sometimes you would like to specify the width of your columns using a percentage. Unfortunately it’s not a native feature of JavaFX 2. Well this ain’t a problem because, again, it is very simple to implement it yourself by creating a custom control.
PTableColumn
Creating a custom control in our case is very simple because what we need to do it basically already done. Indeed what we need is to know the size of our table and then compute our column’s width according a given percentage. All others behaviours are already managed by the TableColumn class. So we will create a class named PTableColumn (‘P’ standing obviously for percentage) and which extends the TableColumn class.
public class PTableColumn<S, T> extends javafx.scene.control.TableColumn<S, T> {
private final DoubleProperty percentageWidth = new SimpleDoubleProperty(1);
public PTableColumn() {
tableViewProperty().addListener(new ChangeListener<TableView<S>>() {
@Override
public void changed(ObservableValue<? extends TableView<S>> ov, TableView<S> t, TableView<S> t1) {
if(PTableColumn.this.prefWidthProperty().isBound()) {
PTableColumn.this.prefWidthProperty().unbind();
}
PTableColumn.this.prefWidthProperty().bind(t1.widthProperty().multiply(percentageWidth));
}
});
}
public final DoubleProperty percentageWidthProperty() {
return this.percentageWidth;
}
public final double getPercentageWidth() {
return this.percentageWidthProperty().get();
}
public final void setPercentageWidth(double value) throws IllegalArgumentException {
if(value >= 0 && value <= 1) {
this.percentageWidthProperty().set(value);
} else {
throw new IllegalArgumentException(String.format("The provided percentage width is not between 0.0 and 1.0. Value is: %1$s", value));
}
}
}
As you can notice, we add a listener to the TableView property of the TableColumn. So each time the table changes, you just update the column’s width. The prefWidthProperty is bound to our percentageWidthPropery using a NumberBinding. So each time our property changes, the width is recalculated.
Use it
Now the only thing left to do is use our custom column in our FXML. Don’t forget to import it!
<!-- ... -->
<?import com.twasyl.envviewer.controls.*?>
<!-- ... -->
<TableView fx:id="propertiesTable">
<columns>
<PTableColumn text="Type" fx:id="typeColumn" percentageWidth="0.08">
<!-- ... -->
</PTableColumn>
<!-- ... -->
</columns>
</TableView>
Well as I said, really easy.
The source code is available here.

