user3804927 user3804927 - 2 months ago 18
Java Question

Using a recursive method to publish a Java SwingWorker process

I have a recursive method that takes a list of file paths from the user and iterate through them recursively to find all files. This may take a while, so I needed a progress dialog. I've coded a SwingWorker thread in an attempt to publish each file to the progress dialog. However, because my method is of a recursive nature, it needs to be in its own method, not the doInBackground() method provided by the SwingWorker library.

Here is a simplified version of my SwingWorker code:

SwingWorker<Boolean, String> worker = (new SwingWorker<Boolean, String>() {
protected Boolean doInBackground() throws Exception {
for (int i = 0; i < model.size(); i++) {
File currentDir = new File(model.get(i));
searchFiles(currentDir); // The recursive method
}
return true;
}

protected void process(List<String> chunks) {
jpanel.someLabel.addFile(chunks.toString());
}
});
worker.execute();


Here is a simplified version of my Recursive code:

private void searchFiles(File fn) {
if (fn.isDirectory()) {
String[] subDir = fn.list();
if (subDir != null) {
for (String fn2 : subDir) {
searchFiles(new File(fn, fn2));
}
}
} else { // If fn isn't a directory, then it must be a file
String absoluteFile = fn.getAbsoluteFile().toString();
publish(absoluteFile); // This isn't working... How can I get this method to publish to process()?
}
}


Is there a way for me to call publish() from another method?

Answer

As the SwingWorker documentation for the publish() method says link

Sends data chunks to the process(java.util.List) method. This method is to be used from inside the doInBackground method to deliver intermediate results for processing on the Event Dispatch Thread inside the process method.

So the answer to your question,You CANNOT call publish() from another method.

However, you can move your recursive method into your SwingWorker class if you really want to call publish() inside the recursive method. Like this:

SwingWorker<Boolean, String> worker = (new SwingWorker<Boolean, String>() {
    protected Boolean doInBackground() throws Exception {
        for (int i = 0; i < model.size(); i++) {
            File currentDir = new File(model.get(i));
            searchFiles(currentDir); // The recursive method
        }
        return true;
    }

    protected void process(List<String> chunks) {
        jpanel.someLabel.addFile(chunks.toString());
    }

    private void searchFiles(File fn) {
        if (fn.isDirectory()) {
            String[] subDir = fn.list();
            if (subDir != null) {
                for (String fn2 : subDir) {
                searchFiles(new File(fn, fn2));
            }
        }
        } else { // If fn isn't a directory, then it must be a file
            String absoluteFile = fn.getAbsoluteFile().toString();
            publish(absoluteFile);
        }
    }

});
worker.execute();