JavaFX: Setting an exact height for list view

In an earlier example, I have used SetMaxheight() to limit the height of the list view.

This is the statement that I have used:


We can make some changes to this line to set the exact height of the list view.

First we have to know that the default row height for JavaFX is 24px.  Then, depending on the number of items in the list, we use the following method to calculate the total row height needed.

items.size() * row_height

The example is as shown below.

package javafxapplication29;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class JavaFXApplication29 extends Application {

    public void start(Stage stage) {

        stage.setTitle("JavaFX Program!");

        ListView<String> lv = new ListView<String>();

        ObservableList<String> items = FXCollections.observableArrayList(
                "Rock", "Country", "Pop", "Rap");

        int row_height = 24;  //default row height
        lv.setMaxHeight(items.size() * row_height);


        HBox hboxPane = new HBox(10); // spacing = 10       
        hboxPane.setPadding(new Insets(10, 10, 10, 10));

        Label lb = new Label("Selection:");

        hboxPane.getChildren().addAll(lb, lv);

        Scene scene = new Scene(hboxPane, 450, 300);

    public static void main(String[] args) {



Series Navigation<< JavaFX: Using FXCollections class to create the list
JavaFX: Setting up menu in a window >>