recursive searchfile method on button clicked

89 views Asked by At

I've written a recursive search method in java GUI application to find a file in a drive. UI is responsive, Search happened successfully but jlist does not populate,whereas console prints file names successfully, after 3 clicks files are added in jlist but with repeated names of each file

 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();

}                             
1

There are 1 answers

3
Mauricio Gracia Gutierrez On

Use a thread or async task for the search method to avoid blocking the UI

https://www3.ntu.edu.sg/home/ehchua/programming/java/J5e_multithreading.html

When the search finishes then you update your UI