longtask.java

来自「通讯采集软件」· Java 代码 · 共 101 行

JAVA
101
字号
package collector.gui.test;

/** Uses a SwingWorker to perform a time-consuming (and utterly fake) task. */

/*
 * LongTask.java is used by:
 *   ProgressBarDemo.java
 *   ProgressBarDemo2.java
 *   ProgressMonitorDemo
 */
public class LongTask {
  private int lengthOfTask;
  private int current = 0;
  private boolean done = false;
  private boolean canceled = false;
  private String statMessage;

  public LongTask() {
    //Compute length of task...
    //In a real program, this would figure out
    //the number of bytes to read or whatever.
    lengthOfTask = 1000;
  }

  /**
   * Called from ProgressBarDemo to start the task.
   */
  public void go() {
    final SwingWorker worker = new SwingWorker() {
      public Object construct() {
        current = 0;
        done = false;
        canceled = false;
        statMessage = null;
        return new ActualTask();
      }
    };
    worker.start();
  }

  /**
   * Called from ProgressBarDemo to find out how much work needs
   * to be done.
   */
  public int getLengthOfTask() {
    return lengthOfTask;
  }

  /**
   * Called from ProgressBarDemo to find out how much has been done.
   */
  public int getCurrent() {
    return current;
  }

  public void stop() {
    canceled = true;
    statMessage = null;
  }

  /**
   * Called from ProgressBarDemo to find out if the task has completed.
   */
  public boolean isDone() {
    return done;
  }

  /**
   * Returns the most recent status message, or null
   * if there is no current status message.
   */
  public String getMessage() {
    return statMessage;
  }

  /**
   * The actual long running task.  This runs in a SwingWorker thread.
   */
  class ActualTask {
    ActualTask() {
      //Fake a long task,
      //making a random amount of progress every second.
      while (!canceled && !done) {
        try {
          Thread.sleep(1000); //sleep for a second
          current += Math.random() * 100; //make some progress
          if (current >= lengthOfTask) {
            done = true;
            current = lengthOfTask;
          }
          statMessage = "Completed " + current +
              " out of " + lengthOfTask + ".";
        }
        catch (InterruptedException e) {
          System.out.println("ActualTask interrupted");
        }
      }
    }
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?