[英]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.