Java Swing How to - Check SwingWorker state








Question

We would like to know how to check SwingWorker state.

Answer

//from w w w.  j av a  2  s  .c  o m
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new TestPane());
    frame.pack();
    frame.setVisible(true);
  }
}
class ProgressWorker extends SwingWorker<Object, Object> {
  @Override
  protected Object doInBackground() throws Exception {
    for (int i = 0; i < 100; i++) {
      setProgress(i);
      try {
        Thread.sleep(25);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return null;
  }
}

class TestPane extends JPanel {
  JProgressBar pbProgress = new JProgressBar();
  JButton start;

  public TestPane() {    
    add(pbProgress);
    start = new JButton("Start");
    add(start);
    start.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        start.setEnabled(false);
        ProgressWorker pw = new ProgressWorker();
        pw.addPropertyChangeListener(new PropertyChangeListener() {

          @Override
          public void propertyChange(PropertyChangeEvent evt) {
            String name = evt.getPropertyName();
            if (name.equals("progress")) {
              int progress = (int) evt.getNewValue();
              pbProgress.setValue(progress);
              repaint();
            } else if (name.equals("state")) {
              SwingWorker.StateValue state = (SwingWorker.StateValue) evt
                  .getNewValue();
              switch (state) {
              case DONE:
                start.setEnabled(true);
                break;
              }
            }
          }
        });
        pw.execute();
      }
    });
  }
}