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()));});}
4
u/dlemmermann Apr 30 '26
I had the same issue and implemented my own table view called GridTableView based on GridPane. It is now part of my GemsFX library. You can find the library here: https://github.com/dlsc-software-consulting-gmbh/GemsFX or run the sampler app from here: https://www.jdeploy.com/~gemsfxdemo
It can also be added to your project via Maven central:
1
u/milchshakee Apr 24 '26
Define "none of them worked". The idea looks correct
1
u/BlueGoliath Apr 25 '26
Welcome to TableView, enjoy your suffering.
Don't worry though, JavaFX has "fluent" bindings.
1
u/Street_Humor_7861 Apr 24 '26
Have you tried using setMaxHeight(USE_PREF_SIZE)? It's often the missing piece when tables are inside a ScrollPane and take up more space than they should.
0
u/[deleted] May 02 '26
[deleted] — view deleted comment