从Jlist中删除文件

时间:2015-05-03 22:18:05

标签: java swing file 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);
    }
  }

2 个答案:

答案 0 :(得分:4)

 int selectedIndex = customerList.getSelectedIndex();

我怀疑你想得到selectedIndex()。

我认为你想得到所选的值:

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

答案 1 :(得分: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);
        }          
    }
  }