java.lang.UnsupportedOperationException用于从javafx tableview中删除行

我试图从javafx中的tableview中删除所选记录。 以下是我使用数据填充表的方法:

public void setMainApp(MainAppClass mainApp){ this.mainApp = mainApp; FilteredList filteredData = new FilteredList(mainApp.getFileData(), p -> true); // 2. Set the filter Predicate whenever the filter changes. filterField.textProperty().addListener((observable, oldValue, newValue) -> { filteredData.setPredicate(files -> { // If filter text is empty, display all files. if (newValue == null || newValue.isEmpty()) { return true; } String lowerCaseFilter = newValue.toLowerCase(); if (files.getFileSubject().toLowerCase().indexOf(lowerCaseFilter) != -1) { return true; // Filter matches Subject. } else if (files.getFileDate().toLowerCase().indexOf(lowerCaseFilter) != -1) { return true; // Filter matches last name. } return false; // Does not match. }); }); // 3. Wrap the FilteredList in a SortedList. SortedList sortedData = new SortedList(filteredData); // 4. Bind the SortedList comparator to the TableView comparator. sortedData.comparatorProperty().bind(fileTable.comparatorProperty()); // 5. Add sorted (and filtered) data to the table. fileTable.setItems(sortedData); } 

这就是我如何删除记录:

 @FXML private void deleteFile() { int selectedIndex = fileTable.getSelectionModel().getSelectedIndex(); if (selectedIndex >= 0) { fileTable.getItems().remove(selectedIndex); } else { // Nothing selected. Alert alert = new Alert(AlertType.WARNING); alert.initOwner(mainApp.getPrimaryStage()); alert.setTitle("No Selection"); alert.showAndWait(); } } 

但它给出了java.lang.UnsupportedOperationException错误。 我在我的示例项目中做了同样的事情并且很好。 那么,我该如何解决这个问题呢?

从基础列表中删除数据,而不是过滤/排序列表:

 FileModel selectedItem = fileTable.getSelectionModel().getSelectedItem(); if (selectedItem != null) { mainApp.getFileData().remove(selectedItem); } 

SortedList和FilteredList从AbstractListinheritanceremove方法,该方法不支持remove(index) 。 您必须从源列表中删除该对象( mainApp.getFileData() )由于所选索引可能不是源列表中的正确索引(在过滤之后),因此有一种方法可以在源列表中获取正确的索引

 sortedData.getSourceIndexFor(mainApp.getFileData(), selectedIndex); 

所以你应该改变你的代码

 @FXML private void deleteFile() { int selectedIndex = fileTable.getSelectionModel().getSelectedIndex(); if (selectedIndex >= 0) { int sourceIndex = sortedData.getSourceIndexFor(mainApp.getFileData(), selectedIndex); mainApp.getFileData().remove(sourceIndex); } } 

我已删除此示例中的其他原因以将其减少到最小。