Swingworker with FileVisitor class and walkFileTree(), which iterates internally over a “set” of files in a directory tree; where to publish()?

前端 未结 3 1566
萌比男神i
萌比男神i 2021-01-29 02:15

It seems like the long-running tree walker task should be defined in a class like so:

  public class TreeWalker extends SwingWorker implements         


        
3条回答
  •  面向向阳花
    2021-01-29 03:10

    Since @Madprogrammer didn't use a GUI and DID use get() [which WAITS until execution of doInBackground() finishes], I added a GUI, modified his publish(), and included a call to done(), just as icing on the cake. My own tree walker doesn't work yet, but Mad's shown me the way. Here are the highlights of the new Mad-with-GUI version.

    public class TreeWalkerExample {
    
      static GUI gui;
    
      public static void main(String args[]) 
      {...invokelater...
         public void run() { 
           gui = new GUI(); 
           gui.setVisible(true); }
       }
    
          public TreeWalkerExample() { 
            (new TreeWalker()).execute();  
          }
    
          public class TreeWalker extends SwingWorker implements FileVisitor {
    
              protected Void doInBackground() throws Exception {
                  Path p = Paths.get("C:\\","Users","\\Dave","\\Documents","\\Java");
                  gui.appendOutput(p.toString());
                  Files.walkFileTree(p, this);
                  return null;
              }
    
              public FileVisitResult visitFile(Path file, BasicFileAttributes a) throws IOException{
                  publish(file);
                  return FileVisitResult.CONTINUE;
              }
    
              protected void process(List chunks) {
                  for (Path p : chunks) 
                    gui.appendOutput(p.getFileName().toString());
              }
    
              protected void done(){
                  gui.appendOutput("\nDone");
              }
        }
        ===================================================================================================
        public class GUI extends javax.swing.JFrame {
    
          JTextArea output;
    
          private void btnWalkMouseClicked(java.awt.event.MouseEvent evt) {                                     
            new TreeWalkerExample();
          }                                    
    
          public void appendOutput(String s){
            output.append("\n" + s);
          }
    

提交回复
热议问题