从 Jlist 中删除文件

Delete File from Jlist

不知道我做错了什么。我试图从我的目录中删除选定的文件,但它只是从列表中删除它。谢谢

  private void deletecustButtonActionPerformed(java.awt.event.ActionEvent evt) {
    DefaultListModel model = (DefaultListModel) customerList.getModel();

    int selectedIndex = customerList.getSelectedIndex();
    File customer = new File("Customers/" + selectedIndex);
    if (selectedIndex != 1) {
      customer.delete();
      model.remove(selectedIndex);
    }
  }
 int selectedIndex = customerList.getSelectedIndex();

我怀疑你想要获取 selectedIndex()。

我认为您想获得所选值:

String fileName = customerList.getSelectedValue().toString();
File customer = new File("Customers/" + fileName);

如果要一键删除列表中选中的多个文件:

private void deletecustButtonActionPerformed(java.awt.event.ActionEvent evt) {
    String fileName;
    DefaultListModel model = (DefaultListModel) customerList.getModel();
    // Get the number of selected files 
    // (corresponding of the size of the int[] customerList.getSelectedIndices() ).
    int numberOfSelections = customerList.getSelectedIndices().length;
    int selectedIndex=0;
    File customer = null;
    // Loop to remove all selected items except your n#1 cust.
    // We begin at the end because the list will be "cut" each turn of the loop
    for(int i = numberOfSelections-1; i >=0 ; i--){
        // Get the selected index
        selectedIndex = customerList.getSelectedIndices()[i];
        if (selectedIndex != 1) {
            fileName = model.getElementAt(selectedIndex);
            customer = new File("Customers/" + fileName );
            customer.delete();
            model.remove(selectedIndex);
        }          
    }
  }