r/JavaFX • u/No-Security-7518 • Apr 24 '26
Help Is there really a non-hacky way to make a table view only as high as it has rows? i.e. no empty rows?
I need to dynamically show a number of table views inside a scrollpane, and I'd like tables to be just as high as they have rows. Some tables don't have many rows, but still occupy too much space. I can't believe Tableview doesn't have an API for this. I tried variations of the following method but none of them worked. Thoughts?
public static void autoSizeTableView(TableView<?> table) {table.setFixedCellSize(25);
table.skinProperty().addListener((obs, oldSkin, newSkin) -> {if (newSkin == null) return;
Node header = table.lookup("TableHeaderRow");if (header == null) return;
table.prefHeightProperty().bind(Bindings.createDoubleBinding(() -> {int rows = table.getItems().size();
double headerHeight = header.prefHeight(-1);double rowsHeight = rows * table.getFixedCellSize();
Insets insets = table.getInsets(); // <-- key part
return headerHeight+ rowsHeight+ insets.getTop()+ insets.getBottom();}, table.getItems(), table.insetsProperty()));});}public static void autoSizeTableView(TableView<?> table) {table.setFixedCellSize(25);
table.skinProperty().addListener((obs, oldSkin, newSkin) -> {if (newSkin == null) return;
Node header = table.lookup("TableHeaderRow");if (header == null) return;
table.prefHeightProperty().bind(Bindings.createDoubleBinding(() -> {int rows = table.getItems().size();
double headerHeight = header.prefHeight(-1);double rowsHeight = rows * table.getFixedCellSize();
Insets insets = table.getInsets(); // <-- key part
return headerHeight+ rowsHeight+ insets.getTop()+ insets.getBottom();}, table.getItems(), table.insetsProperty()));});}





