0

I have a big program which needs to be called by a GUI. The GUI has a progress bar which needs to be updated(like 5% .... 10% )after the user presses the start button. The problem is that the background task performed does not have a fixed execution time. So is somehow possible to measure the progress of the task performed in the doInBackground() method (i am trying to use SwingWorker). Or should i go with an indeterminate progress bar. I was unable to clearly understand the example provided on Oracle's tutorial page and wasn't able to find a decent page explaining how to use a progress bar. Any help will be highly appreciated.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Sashank
  • 101
  • 1
  • 4
  • http://stackoverflow.com/questions/277007/how-to-use-jprogressbar is really similar to your question. – MemLeak Mar 06 '14 at 14:53
  • @MemLeak the input to my program does not have a fixed size and accordingly the execution time varies. The program uses Genetic Algorithm and is implemented using thread. – Sashank Mar 06 '14 at 15:05
  • sorry @ user3313050 i cant do that . But can you explain how the "public void propertyChange(PropertyChangeEvent evt)" method works in the given [link](http://docs.oracle.com/javase/tutorial/uiswing/components/progress.html) – Sashank Mar 06 '14 at 15:08

1 Answers1

1

According to the problem, I would use a infinite progress bar

public class Indeterminate extends JProgressBar {

    private static final long serialVersionUID = -281761375041347893L;

    /***
     * initial the ProgressBar 
     */
    public IndeterminateProgressBar() {
        super();
        setIndeterminate(true);
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                setVisible(false);
            }
        });
    }

    /**
     * call this, if you start a long action
     */
    public void start() {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                setVisible(true);
            }
        });
    }

    /**
     * if you have finished, call this
     */
    public void end() {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                setVisible(false);
            }
        });
    }

}

Used like this:

ActionListener startButtonListener = new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {

        new Thread(new Runnable() {

            @Override
            public void run() {

                try {
                    progressBar.start();
                    // long operation

                } catch (Exception e) {
                    // handle excpetion
                } finally {
                    progressBar.end();

                }

            }
        }).start();

    }
};
MemLeak
  • 4,456
  • 4
  • 45
  • 84