-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStarBoard3.java
More file actions
96 lines (78 loc) · 2.03 KB
/
StarBoard3.java
File metadata and controls
96 lines (78 loc) · 2.03 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
import java.awt.*;
import javax.swing.JPanel;
import javax.swing.ImageIcon;
// uses a thread for animation instead of any timer
// CHANGE #1
// implement Runnable interface
public class StarBoard3 extends JPanel implements Runnable
{
private Image star;
private Thread animator; // CHANGE #2: use thread instead
private int x, y;
private final int DELAY = 50; // CHANGE #3: create delay constant
public StarBoard3()
{
ImageIcon ii = new ImageIcon( getClass().getResource( "tako.png" ) );
star = ii.getImage();
// this jpanel component will use a buffer to paint
// all drawings will be done in memory first on the off-screen buffer
// then copy what's on the off-screen buffer to the screen
setDoubleBuffered( true );
x = 10;
y = 10;
// CHANGE #4: remove timer statements
}
// CHANGE #5:
// this method is called after the JPanel is added to the JFrame component
public void addNotify()
{
super.addNotify();
animator = new Thread( this );
animator.start();
}
// all the drawing is done in this method
public void paint( Graphics g )
{
super.paint( g );
Graphics2D g2d = ( Graphics2D )g;
// do drawings
g2d.drawImage( star, x, y, this );
}
// CHANGE #6:
// change this work to a repeatable method
public void cycle()
{
x++;
y++;
if( y > 200 )
{
x = x - 90;
y = y - 90;
}
repaint();
}
// CHANGE #7:
// add a new method where the animation takes place
public void run()
{
long beforeTime, timeDiff, sleepTime;
beforeTime = System.currentTimeMillis();
while( true )
{
cycle();
timeDiff = System.currentTimeMillis() - beforeTime;
sleepTime = DELAY - timeDiff;
if( sleepTime < 0 )
sleepTime = 2;
try
{
Thread.sleep( sleepTime );
}
catch( InterruptedException e )
{
System.err.println( "interrupted" );
}
beforeTime = System.currentTimeMillis();
}
}
}