JavaFX: Getting selected item from listview

This entry is part 37 of 55 in the series JavaFX

To continue our example from List View, we will work out an example where only one item could be selected from a List View.  This is actually the default setting for List View in JavaFX.

For a single item selection, the method to get the selected item is similar to Choice Box, that is, by using a change listener.

package javafxapplication29;

import javafx.application.Application;
import static javafx.application.Application.launch;
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.scene.paint.Color;
import javafx.stage.Stage;

public class JavaFXApplication29 extends Application {

    @Override
    public void start(Stage stage) {

        stage.setTitle("JavaFX Program!");

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

        lv.getItems().add("Rock");
        lv.getItems().add("Country");
        lv.getItems().add("Rap");
        lv.setMaxHeight(120);

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

        Label lb = new Label("Selection:");
        Label lb1 = new Label("Selected Item");

        lv.getSelectionModel().selectedItemProperty().addListener((ObservableValue, oldValue, newValue) -> {
            lb1.setText(newValue);
        });
        
        lb1.setTextFill(Color.BLUE);

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

        Scene scene = new Scene(hboxPane, 400, 300);
        stage.setScene(scene);

        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

 

lvs

If non should be selected in the beginning, you can use the statement below.

lv.getSelectionModel().select(0);
Series Navigation<< JavaFX: Setting up list view
JavaFX: Using FXCollections class to create the list >>