-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSquish.java
More file actions
109 lines (87 loc) · 2.16 KB
/
Copy pathSquish.java
File metadata and controls
109 lines (87 loc) · 2.16 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
104
105
106
107
108
109
package threadbook.ch11;
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import javax.swing.*;
public class Squish extends JComponent {
private Image[] frameList;
private long msPerFrame;
private volatile int currFrame;
private Thread internalThread;
private volatile boolean noStopRequested;
public Squish(
int width,
int height,
long msPerCycle,
int framesPerSec,
Color fgColor
) {
setPreferredSize(new Dimension(width, height));
int framesPerCycle =
(int) ( ( framesPerSec * msPerCycle ) / 1000 );
msPerFrame = 1000L / framesPerSec;
frameList =
buildImages(width, height, fgColor, framesPerCycle);
currFrame = 0;
noStopRequested = true;
Runnable r = new Runnable() {
public void run() {
try {
runWork();
} catch ( Exception x ) {
// in case ANY exception slips through
x.printStackTrace();
}
}
};
internalThread = new Thread(r);
internalThread.start();
}
private Image[] buildImages(
int width,
int height,
Color color,
int count
) {
BufferedImage[] im = new BufferedImage[count];
for ( int i = 0; i < count; i++ ) {
im[i] = new BufferedImage(
width, height, BufferedImage.TYPE_INT_ARGB);
double xShape = 0.0;
double yShape =
( (double) ( i * height ) ) / (double) count;
double wShape = width;
double hShape = 2.0 * ( height - yShape );
Ellipse2D shape = new Ellipse2D.Double(
xShape, yShape, wShape, hShape);
Graphics2D g2 = im[i].createGraphics();
g2.setColor(color);
g2.fill(shape);
g2.dispose();
}
return im;
}
private void runWork() {
while ( noStopRequested ) {
currFrame = ( currFrame + 1 ) % frameList.length;
repaint();
try {
Thread.sleep(msPerFrame);
} catch ( InterruptedException x ) {
// reassert interrupt
Thread.currentThread().interrupt();
// continue on as if sleep completed normally
}
}
}
public void stopRequest() {
noStopRequested = false;
internalThread.interrupt();
}
public boolean isAlive() {
return internalThread.isAlive();
}
public void paint(Graphics g) {
g.drawImage(frameList[currFrame], 0, 0, this);
}
}