MonitoringTask.java 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package com.its.vds.ui;
  2. import javax.swing.*;
  3. import java.util.concurrent.atomic.AtomicBoolean;
  4. public class MonitoringTask {
  5. private static final int TASK_LENGTH = 1000;
  6. private AtomicBoolean isStarted = new AtomicBoolean(false);
  7. private AtomicBoolean isRunning = new AtomicBoolean(false);
  8. private AtomicBoolean isDone = new AtomicBoolean(false);
  9. private int lengthOfTask;
  10. private int current = 0;
  11. private String statMessage;
  12. public MonitoringTask() {
  13. lengthOfTask = TASK_LENGTH;
  14. }
  15. public void go() {
  16. isRunning.set(true);
  17. if (!isStarted.get()) {
  18. isDone.set(false);
  19. isStarted.set(true);
  20. statMessage = null;
  21. current = 0;
  22. final SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
  23. @Override
  24. protected Void doInBackground() throws Exception {
  25. // Fake a long task, making a random amount of progress every second.
  26. while (!isDone.get()) {
  27. if (isRunning.get()) {
  28. try {
  29. Thread.sleep(1000); // sleep for a second
  30. current += Math.random() * 100; // make some progress
  31. if (current >= lengthOfTask) {
  32. onDown();
  33. current = lengthOfTask;
  34. }
  35. statMessage = "Completed " + current + " out of " + lengthOfTask + ".";
  36. } catch (InterruptedException e) {
  37. e.printStackTrace();
  38. }
  39. }
  40. }
  41. return null;
  42. }
  43. };
  44. worker.execute();
  45. }
  46. }
  47. public void pause() {
  48. this.isRunning.set(false);
  49. }
  50. /**
  51. * Called from SwingTimerDemo to find out how much work needs to be done.
  52. */
  53. public int getLengthOfTask() {
  54. return lengthOfTask;
  55. }
  56. /**
  57. * Called from SwingTimerDemo to find out how much has been done.
  58. */
  59. public int getCurrent() {
  60. return current;
  61. }
  62. public void onDown() {
  63. isDone.set(true);
  64. isStarted.set(false);
  65. isRunning.set(false);
  66. statMessage = null;
  67. }
  68. /**
  69. * Called from SwingTimerDemo to find out if the task has completed.
  70. */
  71. public boolean isDone() {
  72. return isDone.get();
  73. }
  74. /**
  75. * Returns the most recent status message, or null if there is no current
  76. * status message.
  77. */
  78. public String getMessage() {
  79. return statMessage;
  80. }
  81. }