java.lang.UnsupportedOperationException for removing a row from the javafx tableview

后端 未结 2 523
广开言路
广开言路 2021-01-21 19:06

I am trying to delete the selected record from the tableview in javafx. Below is how I am populating the table with the data:

public void setMainApp(MainAppClass         


        
相关标签:
2条回答
  • 2021-01-21 19:44

    Remove the data from the underlying list, not the filtered/sorted list:

    FileModel selectedItem = fileTable.getSelectionModel().getSelectedItem();
    if (selectedItem != null) {
        mainApp.getFileData().remove(selectedItem);
    }
    
    0 讨论(0)
  • 2021-01-21 19:45

    SortedList and FilteredList inherit the remove method from AbstractList which does not support remove(index). You have to remove the object from the source list (mainApp.getFileData()) As the selected index might not be the correct index in the source list (after filtering), there is a method to get the correct index in the source list

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

    So you should change your code to

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

    I have removed the else cause in this example to reduce it to the minimum.

    0 讨论(0)
提交回复
热议问题