EDT is not working properly with recursive method

2019-01-29 13:10发布

问题:

//search files and directories

public  void getFile1(String directoryName) throws Exception {

    File directory = new File(directoryName);
    String str = directory.getName();
    File[] fList = directory.listFiles();
    if (fList != null) {
        for (File file : fList) {
            {                        

            if (file.isFile()) 
            {
                st = (file.toString());                 

               System.out.println(st);    
                jLable1.setText(st);//jLable1 is not updating.


                String fileName = file.getName();
                String strvirusCount=Integer.toString(virusCount); 
               }
            else if (file.isDirectory())

                    {
                      getFile1(file.getAbsolutePath());

                    }               

             globalCount++;       


    }

}

//while retrieving all files and folder unable to update label when process start to with retrieving path Swing form get unresponsive.

回答1:

You're executing a task that takes a long time (iterating through every file, recursively), from the event dispatch thread. So, while this method is executing, the EDT can't do anything else. So it can't do what it's supposed to do: repaint the components and react to user events.

This task should be done in a separate thread, using for example a SwingWorker, which will notify its progress regularly in order to update the label text. The javadoc has examples.