Good day. Began to learn JavaFX. I can not figure out how to remove / add the selected attribute from the checkboxes in the listView, at the moment I can only get what the user has chosen. Here is the piece of code that was used.

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("CheckBox для " + item + " изменен с " + wasSelected + " в " + isNowSelected) ); return observable; } })); 

    1 answer 1

    What you parameterize your list must contain a sign that the item is selected or not. Here is a simple example that demonstrates this behavior.

     ListView < MyItem > listView = new ListView < > (); listView.setCellFactory(p - > new ListCell < MyItem > () { private CheckBox checkBox = new CheckBox(); @Override protected void updateItem(MyItem item, boolean empty) { super.updateItem(item, empty); if (item != null && !empty) { checkBox.selectedProperty().addListener((observable, oldValue, newValue) -> { item.setSelected(newValue); System.out.println("CheckBox для " + item + " изменен с " + oldValue + " в " + newValue); }); checkBox.setText(item.getView()); setGraphic(checkBox); } else { setGraphic(null); } } }); 

    and the MyItem class itself

     public class MyItem { private String view; private boolean isSelected; public MyItem(String view) { this(view, false); } public MyItem(String view, boolean isSelected) { this.view = view; this.isSelected = isSelected; } //getters and setters }