EDT is not working properly with recursive method

2019-01-29 13:07发布

//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条回答
走好不送
2楼-- · 2019-01-29 13:34

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.

查看更多
登录 后发表回答