I\'m using this table to display data in Table View:
import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans
If you're not wedded to bindings, a simple way to do this is to calculate the desired height based on the fixed cell size (cf. Fred Danna's answer) and update it with a listener on the table data.
static void setTableHeightByRowCount(TableView table, ObservableList data) {
int rowCount = data.size();
TableHeaderRow headerRow = (TableHeaderRow) table.lookup("TableHeaderRow");
double tableHeight = (rowCount * table.getFixedCellSize())
// add the insets or we'll be short by a few pixels
+ table.getInsets().getTop() + table.getInsets().getBottom()
// header row has its own (different) height
+ (headerRow == null ? 0 : headerRow.getHeight())
;
table.setMinHeight(tableHeight);
table.setMaxHeight(tableHeight);
table.setPrefHeight(tableHeight);
}
In start(Stage), we create the table and add a ListChangeListener:
TableView table = new TableView<>();
table.setFixedCellSize(24);
table.getItems().addListener((ListChangeListener) c ->
setTableHeightByRowCount(table, c.getList()));
// init scene etc...
stage.show();
table.getItems().addAll("Stacey", "Kristy", "Mary Anne", "Claudia");
Note that the table header row doesn't exist till after stage.show(), so the simplest thing to do is to wait to set the table data till then.
Alternatively, we could set the data at table construction time, and then call setTableHeightByRowCount() explicitly:
TableView table = new TableView<>(
FXCollections.observableArrayList("Stacey", "Kristy", "Mary Anne", "Claudia")
);
// add listener, init scene etc...
stage.show();
setTableHeightByRowCount(table, table.getItems());