Java SwingWorker handle time consuming task

Description

Java SwingWorker handle time consuming task

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutionException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;

class MyPanel extends JPanel {

  static SwingWorker<Boolean, String> copyWorker;
  final int numFiles = 30;

  public MyPanel() {
    setLayout(new BorderLayout());
    JPanel topArea = new JPanel();
    final JLabel label = new JLabel("Files Transfer:", JLabel.CENTER);
    topArea.add(label);//w w  w  . ja v  a  2 s. com
    final JProgressBar progressBar = new JProgressBar();
    progressBar.setIndeterminate(false);
    progressBar.setStringPainted(true);
    progressBar.setMinimum(0);
    progressBar.setMaximum(numFiles);

    topArea.add(progressBar);
    add(topArea, BorderLayout.NORTH);

    // build buttons start and cancel
    JPanel buttonsArea = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    final JButton startButton = new JButton("Start");
    final JButton cancelButton = new JButton("Cancel");
    cancelButton.setEnabled(false);
    buttonsArea.add(startButton);
    buttonsArea.add(cancelButton);
    // create the buttons area
    add(buttonsArea, BorderLayout.SOUTH);

    // build status area
    final JTextArea textArea = new JTextArea(5, 15);
    textArea.setEditable(false);
    JScrollPane statusScroll = new JScrollPane(textArea);
    add(statusScroll, BorderLayout.CENTER);

    // spawn a worker thread
    startButton.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        startButton.setEnabled(false);
        progressBar.setValue(0);
        textArea.setText("");
        cancelButton.setEnabled(true);
        copyWorker = createWorker(numFiles, startButton, cancelButton, textArea, progressBar);
        copyWorker.execute();
      }
    });

    // cancel button will kill worker and reset.
    cancelButton.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        startButton.setEnabled(true);
        cancelButton.setEnabled(false);
        copyWorker.cancel(true);
        progressBar.setValue(0);

      }
    });

  }

  public SwingWorker<Boolean, String> createWorker(final int numFiles, final JButton startButton,
      final JButton cancelButton, final JTextArea status, final JProgressBar pBar) {

    return new SwingWorker<Boolean, String>() {
      // Not on the EDT
      @Override
      protected Boolean doInBackground() throws Exception {
        for (int i = 0; i < numFiles; i++) {
          long elapsedTime = System.currentTimeMillis();
          doTask("some file", "some dest file");
          elapsedTime = System.currentTimeMillis() - elapsedTime;
          String status = elapsedTime + " milliseconds";
          // queue up status
          publish(status);
        }
        return true;
      }

      // On the EDT
      @Override
      protected void process(List<String> chunks) {
        super.process(chunks);
        // with each update gui
        for (String chunk : chunks) {
          status.append(chunk + "\n");
          pBar.setValue(pBar.getValue() + 1);
        }
      }

      // On the EDT
      @Override
      protected void done() {
        try {
          if (isCancelled()) {
            status.append("File transfer was cancelled.\n");
            return;
          }
          Boolean ack = get();
          if (Boolean.TRUE.equals(ack)) {
            status.append("All files were transferred successfully.\n");
          }
          startButton.setEnabled(true);
          cancelButton.setEnabled(false);
        } catch (InterruptedException ex) {
          status.append("File transfer was interupted.\n");
          ex.printStackTrace();
        } catch (ExecutionException ex) {
          ex.printStackTrace();
        }
      }
    };
  }

  public void doTask(String src, String dest) throws InterruptedException {
    Random rnd = new Random(System.currentTimeMillis());
    long millis = rnd.nextInt(1000);
    Thread.sleep(millis);
  }
}

public class Main {
  public static void main(String[] args) {
    // create frame for Main
    JFrame frame = new JFrame("java2s.com");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.add(new MyPanel());
    frame.setSize(300, 250);
    frame.setVisible(true);
  }
}



PreviousNext

Related