Java Swing How to - Use SwingWorker and JProgressBar








Question

We would like to know how to use SwingWorker and JProgressBar.

Answer

import java.awt.GridLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;
/*from  w  ww . ja  va  2 s .com*/
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;

public class Main {
  public static void main(String[] args) {
    TwoRoot t = new TwoRoot();

  }
}

class TwoRoot extends JFrame {
  JProgressBar progressBar = new JProgressBar(0, 100);
  JLabel label = new JLabel("", JLabel.CENTER);

  public TwoRoot() {
    setLayout(new GridLayout(0, 1));
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    add(progressBar);
    add(label);
    setSize(300, 100);
    setVisible(true);

    progressBar.setIndeterminate(true);
    TwoWorker task = new TwoWorker();
    task.addPropertyChangeListener(new PropertyChangeListener() {

      @Override
      public void propertyChange(PropertyChangeEvent e) {
        if ("progress".equals(e.getPropertyName())) {
          progressBar.setIndeterminate(false);
          progressBar.setValue((Integer) e.getNewValue());
        }
      }
    });
    task.execute();
  }

  class TwoWorker extends SwingWorker<Double, Double> {
    int N = 5;
    double x = 1;

    @Override
    protected Double doInBackground() throws Exception {
      for (int i = 1; i <= N; i++) {
        x = x - i;
        setProgress(i * (100 / N));
        publish(x);
        Thread.sleep(1000); 
      }
      return Double.valueOf(x);
    }

    @Override
    protected void process(List<Double> chunks) {
      for (double d : chunks) {
        label.setText(""+d);
      }
    }
  }
}