0

I have an application that allows the user to search for files and directories (including subfolders and files), however if there are a lot of files being displayed, it takes a while to finish. I thought a progress bar would be good to put in there just to display how much long it will take. Now the problem I'm having is that it starts fine, and ends fine. But everything in between isn't. It starts off with intdeterminate for 1000ms (1s). then it turns off. When its finished it displays 100 on the progressbar. But it never actually updates the progress bar when is processing. I used the examples from the java website to get me this far. This is my full code:

import javax.swing.*;
import javax.swing.filechooser.FileSystemView;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.*;
import java.beans.*;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class ProgressBarTest extends JPanel implements ActionListener, PropertyChangeListener {

    JButton browse, search;
    JTextField directory;
    JList<File> results;
    JScrollPane scrollPane;
    JProgressBar progressBar;
    File file;
    List<File> fileList = new ArrayList<File>();
    Task task;

    private class MyCellRenderer extends DefaultListCellRenderer {
        public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            JLabel l = (JLabel)c;
            File f = (File)value;
            l.setText(f.getName());
            l.setPreferredSize(new Dimension(130, 20));
            l.setIcon(FileSystemView.getFileSystemView().getSystemIcon(f));
            l.setToolTipText(f.getName());
            l.setBorder(BorderFactory.createEmptyBorder(3,3,3,3));

            return l;
        }
    }

    private class Task extends SwingWorker<Void, Void> {
        @Override
        public Void doInBackground() {
            file = new File(directory.getText().trim());
            GetFiles(file);
            File[] fileArray = fileList.toArray(new File[0]);
            results.setListData(fileArray);
            int progress = 0;
            setProgress(0);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ignore) {}
            while (progress < 100) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ignore) {}
                progress += 10;
                setProgress(Math.min(progress, 100));
            }
            return null;
        }
        @Override
        public void done() {
            Toolkit.getDefaultToolkit().beep();
            Toolkit.getDefaultToolkit().beep();
            search.setEnabled(true);
            JOptionPane.showMessageDialog(null, "Finished!");
        }
    }

    public ProgressBarTest() {
        super(new BorderLayout());

        browse = new JButton("Browse");
        browse.setActionCommand("browse");
        browse.addActionListener(this);

        search = new JButton("Search");
        search.setActionCommand("search");
        search.addActionListener(this);

        directory = new JTextField(20);
        directory.setEnabled(false);

        file = new File(System.getProperty("user.home"));
        results = new JList<File>(file.listFiles());
        results.setCellRenderer(new MyCellRenderer());
        results.setLayoutOrientation(JList.HORIZONTAL_WRAP);
        results.setVisibleRowCount(-1);

        scrollPane = new JScrollPane(results, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scrollPane.setPreferredSize(new Dimension(408, 100));

        progressBar = new JProgressBar(0, 100);
        progressBar.setValue(0);
        progressBar.setStringPainted(true);

        JPanel panel = new JPanel();
        panel.add(browse);
        panel.add(directory);
        panel.add(search);

        JPanel otherPanel = new JPanel();
        otherPanel.add(scrollPane);

        JPanel newPanel = new JPanel();
        newPanel.add(progressBar);

        add(panel, BorderLayout.PAGE_START);
        add(otherPanel, BorderLayout.CENTER);
        add(newPanel, BorderLayout.PAGE_END);
        setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(5,5,5,5), BorderFactory.createEtchedBorder()));
    }

    @Override
    public void propertyChange(PropertyChangeEvent event) {
        if (event.getPropertyName() == "progress") {
            int progress = (Integer)event.getNewValue();
            progressBar.setIndeterminate(false);
            progressBar.setValue(progress);
        }
    } // End propertyChange()

    @Override
    public void actionPerformed(ActionEvent event) {
        if (event.getActionCommand().equals("browse")) {
            JFileChooser fileChooser = new JFileChooser(System.getProperty("user.home"));
            fileChooser.setDialogTitle("What folder?");
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            fileChooser.showOpenDialog(this.getParent());

            directory.setText(fileChooser.getSelectedFile().getPath());
        } else if (event.getActionCommand() == "search") {
            progressBar.setIndeterminate(true);
            search.setEnabled(false);
            task = new Task();
            task.addPropertyChangeListener(this);
            task.execute();
        }
    } // End actionPerformed()

    private static void CreateAndShowGUI() {
        JFrame frame = new JFrame("ProgressBar Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JComponent contentPane = new ProgressBarTest();
        contentPane.setOpaque(true);

        frame.setContentPane(contentPane);

        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private void GetFiles(File file) {
        for (File f : file.listFiles()) {
            if (f.isDirectory()) {
                fileList.add(f);
                GetFiles(f);
            } else if (f.isFile()) {
                fileList.add(f);
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                CreateAndShowGUI();
            } // End run()
        }); // End Runnable()
    } // End main
} // end ProgressBarTest
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Vince
  • 2,596
  • 11
  • 43
  • 76
  • `if (event.getPropertyName() == "progress") {`???? – Hovercraft Full Of Eels Mar 04 '17 at 20:20
  • Don't compare Strings using `==` or `!=`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two *object references* are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. – Hovercraft Full Of Eels Mar 04 '17 at 20:20
  • @HovercraftFullOfEels that's what [this example](http://docs.oracle.com/javase/tutorial/uiswing/components/progress.html#indeterminate) did so i left it. I also didn't understand that but it worked in that example so I didn't bother changing it. – Vince Mar 04 '17 at 21:47

0 Answers0