-
Notifications
You must be signed in to change notification settings - Fork 3
/
BouncingBall.java
78 lines (62 loc) · 1.78 KB
/
BouncingBall.java
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
// The program outputs a Ball bouncing inside the Output window. Try varying the size of the Output window for dynamic results.
import java.awt.*;
import javax.swing.*;
public class BouncingBall extends JPanel {
// Box height and width
int width;
int height;
// Ball Size
float radius = 40;
float diameter = radius * 2;
// Center of Call
float X = radius + 50;
float Y = radius + 20;
// Direction
float dx = 3;
float dy = 3;
public BouncingBall() {
Thread thread = new Thread() {
public void run() {
while (true) {
width = getWidth();
height = getHeight();
X = X + dx ;
Y = Y + dy;
if (X - radius < 0) {
dx = -dx;
X = radius;
} else if (X + radius > width) {
dx = -dx;
X = width - radius;
}
if (Y - radius < 0) {
dy = -dy;
Y = radius;
} else if (Y + radius > height) {
dy = -dy;
Y = height - radius;
}
repaint();
try {
Thread.sleep(50);
} catch (InterruptedException ex) {
}
}
}
};
thread.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.YELLOW);
g.fillOval((int)(X-radius), (int)(Y-radius), (int)diameter, (int)diameter);
}
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Bouncing Ball");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1000, 1000);
frame.setContentPane(new BouncingBall());
frame.setVisible(true);
}
}