Search code examples
javaswingswingworker

Looking for files in one class and outputing/progressbar in the other


First problem I'm having is reaching my list's size, in the MainWindow when I'm calling my class' getResult().size() it's zero even though it's increasing finely in the filesearch class(if you print it out during search).

Second is I need help how to make two swingworkers communicate between two classes. In one class it's looking for files, and in MainWindow it's moving progress bar.

I've found that I need to do something with SwingPropertyChangeSupport but I wasn't able to implement it.

I tried creating two swingworkers in each class, one for outputing in MainWindow and the other for search(extending FileSearch class)

And since I'm looking for files recursively I'm not sure if this is the right way to do so

  if (temp.isDirectory()) {
        new FileSearch(getFileNameToSearch(),temp).execute();
}  

this thing ^

public class FileSearch extends SwingWorker<Integer, String> {

private String fileNameToSearch;
private List<String> result;
private File file;

public FileSearch(String fileNameToSearch, File file) {
    this.fileNameToSearch = fileNameToSearch;
    this.file = file;
    result = new ArrayList<>();
}

public String getFileNameToSearch() {
    return fileNameToSearch;
}


public List<String> getResult() {
    return result;
}


@Override
protected Integer doInBackground() throws Exception {
    if (file.isDirectory()) {
        System.out.println("Searching directory ... " + file.getAbsoluteFile());

        if (file.canRead()) {
            try{
                for (File temp : file.listFiles()) {
                    if (temp.isDirectory()) {
                        new FileSearch(getFileNameToSearch(),temp).execute();
                    } else {
                        String temp2 = temp.getName().toLowerCase();
                        String trimmedName = temp.getName().toLowerCase();
                        try{
                            trimmedName = temp2.substring(0, temp2.lastIndexOf("."));
                        }catch(StringIndexOutOfBoundsException e){

                        }
                        if (getFileNameToSearch().equals(trimmedName)) {
                            result.add(temp.getAbsoluteFile().toString());
                            System.out.println(result.size());

                        }else{
                            System.out.println(getFileNameToSearch() + "!= " + trimmedName);
                        }

                    }
                }
            }catch(NullPointerException e){

            }


        } else {
            System.out.println(file.getAbsoluteFile() + "Permission Denied");
        }
    }
    return result.size();
}

And MainWindow

    public class MainWindow extends JFrame {
    public MainWindow() {
    initComponents();
    fileChooser1.setApproveButtonText("Select");
    fileChooser1.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    directoriesTextArea.setEditable(false);

}

private void startButtonMouseClicked(MouseEvent e) {
    directoriesTextArea.setText("");

    SwingWorker<Void, String> worker =  new SwingWorker<>(){
        @Override
        protected Void doInBackground() throws Exception {
            File file = new File(absolutePathTextField.getText());
            FileSearch filesearch = new FileSearch(fileNameTextField.getText(), file);

            filesearch.execute();

            int count = filesearch.getResult().size();

            if(count == 0){
                JOptionPane.showMessageDialog(new JFrame(), "There are no such files");
                System.out.println(count);
            }else{
                for(String matched : filesearch.getResult()){
                    publish(matched);
                }
            }
            return null;
        }

        @Override
        protected void process(List<String> chunks) {
            for(String matched : chunks){
                directoriesTextArea.append(matched + "\n");
            }
        }

        @Override
        protected void done() {
            directoriesTextArea.append("\nDone!");

        }
    };

    worker.execute();


}

=================EDITED VERSION=================

private void startButtonMouseClicked(MouseEvent e) {
    directoriesTextArea.setText("");
    progressBarCounter = 0;
    progressBar1.setValue(0);


    SwingWorker<Void, String> worker = new SwingWorker<Void, String>() {
        List<String> result = new ArrayList<>();

        @Override
        protected Void doInBackground() throws Exception {
            File file = new File(absolutePathTextField.getText());
            FileSearch fileSearch = new FileSearch(fileNameTextField.getText(), file);

            folderCount(file);
            searchFiles(file);

            return null;
        }

        @Override
        protected void process(List<String> chunks) {
            for(String file : chunks){
                directoriesTextArea.append(file + "\n");
            }
        }
        protected void folderCount(File file){
            if (file.isDirectory()) {

                if (file.canRead()) {
                    try {
                        for (File temp : file.listFiles()) {
                            if (temp.isDirectory()) {
                                folderCount(temp);
                                folderCount++;
                            }
                        }
                    } catch (NullPointerException e) {

                    }
                }
            }
            progressBar1.setMinimum(0);
            progressBar1.setMaximum(folderCount);
        }


        protected void searchFiles(File file) {
        progressBarCounter++;
            if (file.isDirectory()) {
                System.out.println("Searching directory ... " + file.getAbsoluteFile());

                if (file.canRead()) {
                    try {
                        for (File temp : file.listFiles()) {
                            progressBar1.setValue(progressBarCounter);
                            if (temp.isDirectory()) {
                                searchFiles(temp);
                            } else {
                                String temp2 = temp.getName().toLowerCase();
                                String trimmedName = temp.getName().toLowerCase();
                                try {
                                    trimmedName = temp2.substring(0, temp2.lastIndexOf("."));
                                } catch (StringIndexOutOfBoundsException e) {

                                }
                                if (fileNameTextField.getText().toLowerCase().equals(trimmedName)) {
                                    System.out.println(fileNameTextField.getText() + " == " + trimmedName);
                                    publish(temp.getAbsolutePath());

                                } else {
                                    System.out.println(fileNameTextField.getText() + "!= " + trimmedName);
                                }

                            }
                        }
                    } catch (NullPointerException e) {

                    }


                } else {
                    System.out.println(file.getAbsoluteFile() + "Permission Denied");
                }
            }
        }
    };
    worker.execute();

}

Solution

  • You are missing the progress / process combination. In the background thread you need to regularly call the process method, to state how far along the background process is. Subsequently, the progress method is called for you (within the EDT thread) and there you can update the progress bar. https://docs.oracle.com/javase/7/docs/api/javax/swing/SwingWorker.html