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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With