小编典典

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

java

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

public void setMainApp(MainAppClass mainApp){
    this.mainApp = mainApp;

    FilteredList<FileModel> 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<FileModel> 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错误。我在示例项目中做了同样的事情,一切顺利。那么,如何解决此问题?


阅读 349

收藏
2020-11-26

共1个答案

小编典典

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

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