我在 java GUI 应用程序中编写了一个递归搜索方法来查找驱动器中的文件。 用户界面响应灵敏, 搜索成功,但 jlist 未填充,而控制台成功打印文件名,单击 3 次后,文件将添加到 jlist 中,但每个文件的名称重复
DefaultListModel lm=new DefaultListModel();
public void search(String path){
File root = new File(path);
File[] list=root.listFiles();
if(list==null){
return;
}
for(File f: list){
if(f.isDirectory()){
if(list==null){
return;
}
search(f.getAbsolutePath());
}
else{
if(f.getName().endsWith(".txt") && f.getName().startsWith("abc")){
lm.addElement(f.getName());
System.out.println(f.getName());
found=true;
}
}
}
private void formWindowOpened(java.awt.event.WindowEvent evt) {
jList1.setModel(lm);
}
private void searchBtnActionPerformed(java.awt.event.ActionEvent evt) {
//just added this code in my program to resolve unresponsive UI
Thread t=new Thread(new Runnable() {
@Override
public void run() {
search("c:\\");
}
});
t.start();
}
最佳答案
对搜索方法使用线程或异步任务以避免阻塞 UI
https://www3.ntu.edu.sg/home/ehchua/programming/java/J5e_multithreading.html
搜索完成后,您将更新您的用户界面
关于java - 单击按钮时的递归搜索文件方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31008297/