Don't know what I'm doing wrong here. I'm trying to delete the selected file from my directory but it's only deleting it from the list. Thanks
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();
I doubt you want to get the selectedIndex().
I would think you want to get the selected value:
String fileName = customerList.getSelectedValue().toString();
File customer = new File("Customers/" + fileName);
If you want to delete several selected files of the list with one click:
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);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.