How do you get JavaFX ListView to be the height of its items?

mentics picture mentics · Jul 2, 2013 · Viewed 28.4k times · Source

If I create a ListView:

new ListView<>(FXCollections.observableArrayList("1", "2", "3"))

I would expect it to create a ListView with 3 rows. But it doesn't. It creates a ListView of 17 or so rows. Is there a way to tell ListView to always be the height such that whatever items are in it are always shown but no blank rows?

Having it auto width would also be useful, so it's always as wide as the widest row.

One purpose of this is that then it could be used in a ScrollPane. I know it has its own scrollbars, but they don't offer sufficient control.

Answer

Alexandre Mazari picture Alexandre Mazari · Jan 28, 2014

I just found out that Paul Marshall's answer can be reducted to a one-liner using Bindings.size that creates a numeric jfx property representing the size of an ObservableList :

listView.prefHeightProperty().bind(Bindings.size(itemListProperty).multiply(LIST_CELL_HEIGHT));

The list cell height must sadly still be hardcoded AFAIK.