JavaFX - Adapt TableView height to number of rows

Just some guy picture Just some guy · Jan 14, 2015 · Viewed 14.1k times · Source

I want my TableView's height to adapt to the number of filled rows, so that it never shows any empty rows. In other words, the height of the TableView should not go beyond the last filled row. How do I do this?

Answer

eckig picture eckig · Jan 14, 2015

If you want this to work you have to set the fixedCellSize.

Then you can bind the height of the TableView to the size of the items contained in the table multiplied by the fixed cell size.

Demo:

@Override
public void start(Stage primaryStage) {

    TableView<String> tableView = new TableView<>();
    TableColumn<String, String> col1 = new TableColumn<>();
    col1.setCellValueFactory(cb -> new SimpleStringProperty(cb.getValue()));
    tableView.getColumns().add(col1);
    IntStream.range(0, 20).mapToObj(Integer::toString).forEach(tableView.getItems()::add);

    tableView.setFixedCellSize(25);
    tableView.prefHeightProperty().bind(tableView.fixedCellSizeProperty().multiply(Bindings.size(tableView.getItems()).add(1.01)));
    tableView.minHeightProperty().bind(tableView.prefHeightProperty());
    tableView.maxHeightProperty().bind(tableView.prefHeightProperty());

    BorderPane root = new BorderPane(tableView);
    root.setPadding(new Insets(10));
    Scene scene = new Scene(root, 400, 400);
    primaryStage.setScene(scene);
    primaryStage.show();
}

Note: I multiplied fixedCellSize * (data size + 1.01) to include the header row.