In my FXMLTableViewController.java I have added a Search feature which uses the Sorted Filtered List to display the search Results (filter results) in the same TableView. This code was taken from here this is what I have implemented in my Project. But it throws exception when I do the usual data2.add(new Entity(""));
public class FXMLTableViewController {
@FXML
private TableView<Entity> tableView;
@FXML
private JFXTextField searchBox;
@FXML
public void initialize() throws IOException, ParseException {
tableView.setItems(data2); //data2 is a observable list returned my another function, it is not related here.
FilteredList<Entity> filteredData = new FilteredList<> (data2, p -> true);
searchBox.textProperty().addListener((observable, oldValue, newValue) -> {
filteredData.setPredicate(person -> {
if (newValue == null || newValue.isEmpty()) {
return true;
}
String lowerCaseFilter = newValue.toLowerCase();
return Person.getPsfName_add().toLowerCase().contains(lowerCaseFilter)
});
});
SortedList<Entity> sortedData = new SortedList<>(filteredData);
sortedData.comparatorProperty().bind(tableView.comparatorProperty());
tableView.setItems(sortedData);
sortedData.add(new Entity("")); //error line
tableView.refresh();
}
}
Now whenever I try to add a new Entity object I get the Error
java.lang.UnsupportedOperationException
This I guess is due to the fact that SortedLists are unmodifiable? How do I solve this? I want to add new Rows at various points in my Project but I also want the Search/Filter Facility.
Sorted (and filtered) lists are unmodifiable. You should modify the underlying list (
data2
), and the sorted/filtered list will update automatically (it is observing the underlyingObservableList
).The code you need looks like:
Note for clarity I removed the first call to
tableView.setItems(...)
as you are only settingitems
to something else immediately afterwards. Also note thattableView.refresh()
is redundant (the table is also observing theObservableList
that makes up its items).