Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX - Adapt TableView height to number of rows

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?

like image 954
Just some guy Avatar asked Jan 14 '15 14:01

Just some guy


1 Answers

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.

like image 92
eckig Avatar answered Oct 11 '22 23:10

eckig