I have a problem with ListView in JavaFX. I replicated the problem in a small application available here on BitBucket. As you see in the GIF below, I have a textfield and a listview containing a set of items coming from a web service. There is only controller in the app, HelloController.java.
I am getting two problems. (1) Items are not being deleted and (2) filtering the listview based on the content of the textview is working but after filtering it, when the textview becomes empty, duplicate items are being added to the listview.
Deleting items from ListView
@FXML protected void deleteItem(){ Privilege selectedItem = lstItems.getSelectionModel().getSelectedItem(); allPrivileges.remove(selectedItem); ObservableList<Privilege> filteredList = FXCollections.observableArrayList(allPrivileges); lstItems.setItems(filteredList); }
Filtering the listview
private void filterPriviledges() { String filter = txtItem.getText(); ObservableList<Privilege> filteredList = FXCollections.observableArrayList( allPrivileges.stream() .filter(privilege -> privilege.getName().toLowerCase().startsWith(filter.toLowerCase())) .collect(Collectors.toList()) ); lstItems.setItems(filteredList); }
Codes to load all Privileges from the web service
void loadPrivileges() throws IOException { Response<List<Privilege>> response = apiService.getPrivileges().execute(); allPrivileges = response.body(); lstItems.setItems(FXCollections.observableArrayList(allPrivileges)); lstItems.setCellFactory( new Callback<ListView<Privilege>, ListCell<Privilege>>() { @Override public ListCell<Privilege> call(ListView<Privilege> param) { return new ListCell<Privilege>() { @Override public void updateItem(Privilege privilege, boolean empty) { super.updateItem(privilege, empty); if (!empty){ setText(privilege.getName()); } } }; } } ); }