2015-05-03 111 views
1

不知道我在這裏做錯了什麼。我試圖從我的目錄中刪除選定的文件,但它只是從列表中刪除它。由於從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); 
    } 
    } 
+0

什麼類型的數據是在清單?另外,你真的應該檢查'File#delete'的返回結果。 – MadProgrammer

回答

4
int selectedIndex = customerList.getSelectedIndex(); 

我懷疑你想要得到的selectedIndex()。

我想你想選擇的值:

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

哈哈謝謝:) –

1

如果你想刪除列表中的幾個選定的文件與點擊:

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); 
     }   
    } 
    }