Sashank
Sashank

Reputation: 101

Updating the progress bar

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.

Upvotes: 0

Views: 172

Answers (1)

MemLeak
MemLeak

Reputation: 4640

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();

    }
};

Upvotes: 1

Related Questions