-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDigitalTimer.java
More file actions
103 lines (83 loc) · 2.25 KB
/
Copy pathDigitalTimer.java
File metadata and controls
103 lines (83 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package threadbook.ch09;
import java.awt.*;
import java.lang.reflect.*;
import java.text.*;
import javax.swing.*;
public class DigitalTimer extends JLabel {
private volatile String timeText;
private Thread internalThread;
private volatile boolean noStopRequested;
public DigitalTimer() {
setBorder(BorderFactory.createLineBorder(Color.black));
setHorizontalAlignment(SwingConstants.RIGHT);
setFont(new Font("SansSerif", Font.BOLD, 16));
setText("00000.0"); // use to size component
setMinimumSize(getPreferredSize());
setPreferredSize(getPreferredSize());
setSize(getPreferredSize());
timeText = "0.0";
setText(timeText);
noStopRequested = true;
Runnable r = new Runnable() {
public void run() {
try {
runWork();
} catch ( Exception x ) {
x.printStackTrace();
}
}
};
internalThread = new Thread(r, "DigitalTimer");
internalThread.start();
}
private void runWork() {
long startTime = System.currentTimeMillis();
int tenths = 0;
long normalSleepTime = 100;
long nextSleepTime = 100;
DecimalFormat fmt = new DecimalFormat("0.0");
Runnable updateText = new Runnable() {
public void run() {
setText(timeText);
}
};
while ( noStopRequested ) {
try {
Thread.sleep(nextSleepTime);
tenths++;
long currTime = System.currentTimeMillis();
long elapsedTime = currTime - startTime;
nextSleepTime = normalSleepTime +
( ( tenths * 100 ) - elapsedTime );
if ( nextSleepTime < 0 ) {
nextSleepTime = 0;
}
timeText = fmt.format(elapsedTime / 1000.0);
SwingUtilities.invokeAndWait(updateText);
} catch ( InterruptedException ix ) {
// stop running
return;
} catch ( InvocationTargetException x ) {
// If an exception was thrown inside the
// run() method of the updateText Runnable.
x.printStackTrace();
}
}
}
public void stopRequest() {
noStopRequested = false;
internalThread.interrupt();
}
public boolean isAlive() {
return internalThread.isAlive();
}
public static void main(String[] args) {
DigitalTimer dt = new DigitalTimer();
JPanel p = new JPanel(new FlowLayout());
p.add(dt);
JFrame f = new JFrame("DigitalTimer Demo");
f.setContentPane(p);
f.setSize(250, 100);
f.setVisible(true);
}
}