-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCarComponent.java
More file actions
80 lines (67 loc) · 1.57 KB
/
Copy pathCarComponent.java
File metadata and controls
80 lines (67 loc) · 1.57 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
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
/**
This component draws two cars
*/
public class CarComponent extends JComponent
{
/**
*
*/
private static final long serialVersionUID = 1L;
private Car car1;
private Car car2;
public CarComponent()
{
car1 = new Car(1200, 100);//car 1 starts on the far left of the screen
car2 = new Car(10, 300); //car 2 starts on the right side of the screen
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
car1.draw(g2);
car2.draw(g2);
}
/**
Starts the animation threads.
*/
public void startCars()
{
class CarRunnable implements Runnable
{
Car car;
int dx;
int dy;
public CarRunnable(Car car, int dx, int dy)
{
this.car = car;
this.dx = dx;
this.dy = dy;
}
public void run()
{
final int DELAY = 10; // speed of the car movement can be set here. Lower the delay time, faster car
final int STEPS = 1150; // travel distance inside the frame
try
{
for (int i = 0; i < STEPS; i++)
{
car.move(dy, dx);
CarComponent.this.repaint();
Thread.sleep(DELAY);
}
}
catch (InterruptedException exception)
{}
}
}
// Creation of car thread and run
Runnable r1 = new CarRunnable(car1, 0, -1); // x and y position lets the car move from left to right
Runnable r2 = new CarRunnable(car2, 0, 1); // right to left position
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
}