Search code examples
javalistviewjavafxlistviewitem

Getting selected Items from a ListView | CheckBoxListCell


I want to create a simple ListView with CheckBox for each item. This has been done. Now I am looking for a way to get all selected Items from this ListView.

I have figured out that I can use the method setCellFactory() to add items when they are selected in a separate Collection and remove them when they are unselected. But I think this is an ugly way to do that.

ListView<String> listView = new ListView<>();
    String[] toppings = {"Cheese", "Pepperoni", "Black Olives"};
    listView.getItems().addAll(toppings);
    listView.setCellFactory(CheckBoxListCell.forListView(new Callback<String, ObservableValue<Boolean>>() {
        @Override
        public ObservableValue<Boolean> call(String item) {
        BooleanProperty observable = new SimpleBooleanProperty();
        observable.addListener((obs, wasSelected, isNowSelected)
            -> System.out.println("Check box for " + item + " changed from " + wasSelected + " to " + isNowSelected)
        );
        return observable;
        }
}));

How can I get the list of selected items from the ListView?


Solution

  • Use this way

    public void start(Stage primaryStage) {
            try {
                ListView<String> listView = new ListView<>();
                Button button = new Button("Get");
                List<String> list = new ArrayList<>();
                String[] toppings = { "Cheese", "Pepperoni", "Black Olives" };
                listView.getItems().addAll(toppings);
                listView.setCellFactory(CheckBoxListCell.forListView(new Callback<String, ObservableValue<Boolean>>() {
                    @Override
                    public ObservableValue<Boolean> call(String item) {
                        BooleanProperty observable = new SimpleBooleanProperty();
                        observable.addListener((obs, wasSelected, isNowSelected) -> {
                            if (isNowSelected) {
                                list.add(item);
                            } else {
                                list.remove(item);
                            }
                        });
                        return observable;
                    }
                }));
    
                button.setOnAction(e -> {
                    for (int i = 0; i < list.size(); i++) {
                        System.out.println(list.get(i));
                    }
                });
    
                VBox root = new VBox();
                root.setAlignment(Pos.CENTER);
                root.getChildren().addAll(listView, button);
                Scene scene = new Scene(root, 300, 250);
                primaryStage.setScene(scene);
                primaryStage.show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }