簡體   English   中英

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM