Hans Pour
Hans Pour

Reputation: 432

How to update a progress bar to show the progress during an activity(when a method is working)?

I searched for this question and I found several documentation but they are too complicated to understand for me.

I just want simply to make progress bar works during an activity not after that.

At the sample codes I provided, the progress bar works after the run method done, not during that. how can I change this code to progress bar is being updated when the run method is working?

I think I have to create a new thread to handle the long-running method but I don't know how to do that?

public class Gui extends JFrame {

private JProgressBar progressBar;
private JButton button;

public Gui() throws HeadlessException {
    super("Progress bar");
    setSize(500, 100);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLayout(new FlowLayout());
    add(resPan());
}

private JPanel resPan() {
    JPanel resPan = new JPanel(new FlowLayout(FlowLayout.CENTER));
    resPan.setPreferredSize(new Dimension(500, 100));

    progressBar = new JProgressBar();
    progressBar.setPreferredSize(new Dimension(180, 40));

    button = new JButton("Action");
    button.setPreferredSize(new Dimension(80, 40));
    button.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent arg0) {
            progressBar.setIndeterminate(true);
            run();
        }

    });

    resPan.add(button);
    resPan.add(progressBar);
    return resPan;
}

private void run() {
    try {
        Thread.sleep(4000);
        //progressBar.setIndeterminate(false);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}}

Upvotes: 0

Views: 3769

Answers (2)

Ezequiel
Ezequiel

Reputation: 3592

In SwingWoerker javadoc you can foun this exact example. A thread runing in a Swingworker and the progress being updated with SwingWorker#setProgress(int progress)

http://docs.oracle.com/javase/7/docs/api/javax/swing/SwingWorker.html

Upvotes: 1

cello
cello

Reputation: 5486

Yes, you have to create a new thread. Otherwise, Swing cannot display anything new (e.g. updating the progress bar) as Swing's thread is still busy with your run method. A simple way would be:

public void actionPerformed(ActionEvent arg0) {
     progressBar.setIndeterminate(true);
     new Thread(new Runnable() {
         @Override
         public void run() {
             // do the long-running work here
             // at the end:
             SwingUtilities.invokeLater(new Runnable() {
                 @Override
                 public void run() {
                     progressBar.setIndeterminate(false);
                 }
             );
         }
     ).start();
}

Note that progressBar must be declared final in order to be used from within the thread's runnable.

Upvotes: 2

Related Questions