DEV Community

Cover image for ListView
Paul Ngugi
Paul Ngugi

Posted on

ListView

A list view is a control that basically performs the same function as a combo box, but it enables the user to choose a single value or multiple values.

Figure below lists several frequently used properties and constructors in ListView. ListView is defined as a generic class. The generic type T specifies the element type for the elements stored in a list view.

Image description

The getSelectionModel() method returns an instance of SelectionModel, which contains the methods for setting a selection mode and obtaining selected indices and items. The selection mode is defined in one of the two constants SelectionMode.MULTIPLE and SelectionMode.SINGLE, which indicates whether a single item or multiple items can be selected. The default value is SelectionMode.SINGLE. Figure below (a) shows a single selection and Figure below (b) and (c) show multiple selections.

Image description

The following statements create a list view of six items with multiple selections allowed.

ObservableList<String> items =
FXCollections.observableArrayList("Item 1", "Item 2",
"Item 3", "Item 4", "Item 5", "Item 6");
ListView<String> lv = new ListView<>(items);
lv.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

The selection model in a list view has the selectedItemProperty property, which is an instance of Observable. You can add a listener to this property for handling the property change as follows:

`lv.getSelectionModel().selectedItemProperty().addListener(
new InvalidationListener() {
public void invalidated(Observable ov) {
System.out.println("Selected indices: "

  • lv.getSelectionModel().getSelectedIndices()); System.out.println("Selected items: "
  • lv.getSelectionModel().getSelectedItems()); } });`

This anonymous inner class can be simplified using a lambda expression as follows:

`lv.getSelectionModel().selectedItemProperty().addListener(ov -> {
System.out.println("Selected indices: "

  • lv.getSelectionModel().getSelectedIndices()); System.out.println("Selected items: "
  • lv.getSelectionModel().getSelectedItems()); });`

The code below gives a program that lets users select the countries in a list view and displays the flags of the selected countries in the image views. Figure below shows a sample run of the program.

Image description

Here are the major steps in the program:

  1. Create the user interface. Create a list view with nine country names as selection values, and place the list view inside a scroll pane. Place the scroll pane on the left of a border pane. Create nine image views to be used to display the countries’ flag images. Create a flow pane to hold the image views and place the pane in the center of the border pane.
  2. Process the event. Create a listener to implement the invalidated method in the InvalidationListener interface to place the selected countries’ flag image views in the pane.
package application;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.SelectionMode;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;

public class ListViewDemo extends Application {
    // Declare an array of Strings for flag titles
    private String[] flagTitles = {"Canada", "China", "Denmark", "France", "Germany", "India", "Norway", "United Kingdom", "United States of America"};

    // Declare an ImageView array for the national flags of 9 countries
    private ImageView[] ImageViews = {new ImageView("file:/C:/Users/Paul/development/MyJavaFX/src/application/image/ke.jpg"), 
            new ImageView("file:/C:/Users/Paul/development/MyJavaFX/src/application/image/lo.jpg"),
            new ImageView("file:/C:/Users/Paul/development/MyJavaFX/src/application/image/ke.jpg"),
            new ImageView("file:/C:/Users/Paul/development/MyJavaFX/src/application/image/ke.jpg"),
            new ImageView("file:/C:/Users/Paul/development/MyJavaFX/src/application/image/ke.jpg"),
            new ImageView("file:/C:/Users/Paul/development/MyJavaFX/src/application/image/ke.jpg"),
            new ImageView("file:/C:/Users/Paul/development/MyJavaFX/src/application/image/ke.jpg"),
            new ImageView("file:/C:/Users/Paul/development/MyJavaFX/src/application/image/ke.jpg"), new ImageView("file:/C:/Users/Paul/development/MyJavaFX/src/application/image/ke.jpg"),};

    @Override // Override the start method in the Application class
    public void start(Stage primaryStage) {
        ListView<String> lv = new ListView<>(FXCollections.observableArrayList(flagTitles));
        lv.setPrefSize(400, 400);
        lv.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

        // Create a pane to hold image views
        FlowPane imagePane = new FlowPane(10, 10);
        BorderPane pane =  new BorderPane();
        pane.setLeft(new ScrollPane(lv));
        pane.setCenter(imagePane);

        lv.getSelectionModel().selectedIndexProperty().addListener(ov -> {
            imagePane.getChildren().clear();
            for(Integer i: lv.getSelectionModel().getSelectedIndices()) {
                imagePane.getChildren().add(ImageViews[i]);
            }
        });

        // Create a scene and place it in the stage
        Scene scene = new Scene(pane, 450, 170);
        primaryStage.setTitle("ListViewDemo"); // Set the stage title
        primaryStage.setScene(scene); // Place the scene in the stage
        primaryStage.show(); // Display the stage
    }

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

Enter fullscreen mode Exit fullscreen mode

The program creates an array of strings for countries (lines 15) and an array of nine image views for displaying flag images for nine countries (lines 18–25) in the same order as in the array of countries. The items in the list view are from the array of countries (line 29). Thus, the index 0 of the image view array corresponds to the first country in the list view.

The list view is placed in a scroll pane (line 36) so that it can be scrolled when the number of items in the list extends beyond the viewing area.

By default, the selection mode of the list view is single. The selection mode for the list view is set to multiple (line 31), which allows the user to select multiple items in the list view. When the user selects countries in the list view, the listener’s handler (lines 39–44) is
executed, which gets the indices of the selected items and adds their corresponding image views to the flow pane.

Top comments (0)