1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.xnap.commons.io;
21
22 import java.awt.Component;
23
24
25 /***
26 *
27 *
28 * Create a top ProgressMonitor with totalSteps set to number of
29 * SubTaskProgressMonitor * SubTaskProgressMonitor amounts.
30 *
31 * <pre>
32 * ProgressMonitor topMonitor = new ProgressDialog();
33 * topMonitor.setTotalSteps(7 * 100);
34 * for (int i = 0; i < 7; i++) {
35 * new SubTaskProgressMonitor(topMonitor, 100, totalStepsOfSubTask);
36 * }
37 * </pre>
38 */
39 public class SubTaskProgressMonitor implements ProgressMonitor {
40
41 private ProgressMonitor monitor;
42 private int workedAmount;
43 private int totalAmount;
44 private long totalSteps;
45 private boolean done;
46 private long value;
47
48 public SubTaskProgressMonitor(ProgressMonitor monitor, int amount, long totalSteps)
49 {
50 if (monitor == null) {
51 throw new IllegalArgumentException();
52 }
53 if (amount < 0) {
54 throw new IllegalArgumentException("amount may not be less than 0");
55 }
56
57 this.monitor = monitor;
58 this.totalAmount = amount;
59
60 setTotalSteps(totalSteps);
61 }
62
63 public long getValue()
64 {
65 return value;
66 }
67
68 public void setTotalSteps(long totalSteps)
69 {
70 if (totalSteps < 0) {
71 throw new IllegalArgumentException("totalSteps may not be less than 0");
72 }
73 if (workedAmount > 0) {
74 throw new IllegalStateException("totalSteps may not be changed after work() or setValue() has been called");
75 }
76 this.totalSteps = totalSteps;
77 }
78
79 public void setValue(long value)
80 {
81 if (done) {
82 throw new IllegalStateException("monitor is already done");
83 }
84 if (value > totalSteps) {
85 throw new IllegalArgumentException("value may not exceed totalSteps (" + value + " > " + totalSteps + ")");
86 }
87 if (this.value == value) {
88 return;
89 }
90 if (value < this.value) {
91 throw new IllegalArgumentException("value may not decrease (" + value + " < " + this.value + ")");
92 }
93
94 this.value = value;
95 double percent = (double)value / totalSteps;
96 int newAmount = (int)(percent * totalAmount);
97 if (newAmount > workedAmount) {
98 monitor.work(newAmount - workedAmount);
99 workedAmount += newAmount - workedAmount;
100 }
101 }
102
103 public void work(long amount)
104 {
105 setValue(value + amount);
106 }
107
108 public void done()
109 {
110 if (done) {
111 return;
112 }
113 done = true;
114 monitor.work(totalAmount - workedAmount);
115 }
116
117 public boolean isCancelled()
118 {
119 return monitor.isCancelled();
120 }
121
122 public void setCancelEnabled(boolean enabled)
123 {
124 monitor.setCancelEnabled(enabled);
125 }
126
127 public void setText(String text)
128 {
129 monitor.setText(text);
130 }
131
132 public Component getComponent()
133 {
134 return monitor.getComponent();
135 }
136
137 }