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
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
110
111
112
113
114
115
//小球碰撞
package practice1;//用eclipse写的,自定义的包名,手动编译的话直接删掉这句

import java.awt.*;
import javax.swing.*;

public class MyTest
{

public static void main(String args[])
{

JFrame w = new JFrame();
w.setSize(800, 600);

MyPanel mp = new MyPanel();
w.add(mp);

Thread t = new Thread(mp);
t.start();

w.setVisible(true);

}
}

class MyPanel extends JPanel implements Runnable
{

int x = 400;
int y = 100;
int att = 0;
public void paint(Graphics g)
{

super.paint(g);
setBackground(Color.black);
g.setColor(Color.white);
g.fillOval(x, y, 20, 20);
}
public void run()
{

while(true)
{
switch(att)
{
case 0:
x++;
y++;
break;
case 1:
x--;
y++;
break;
case 2:
x--;
y--;
break;
case 3:
x++;
y--;
}
if (x > 750)
{
if (att == 0)
{
att = 1;
}
else
{
att = 2;
}
}
if (y > 530)
{
if (att == 1)
{
att = 2;
}
else
{
att = 3;
}
}
if (x < 10)
{
if (att == 2)
{
att = 3;
}
else
{
att = 0;
}
}
if (y < 10)
{
if (att == 3)
{
att = 0;
}
else
{
att = 1;
}
}
try
{
Thread.sleep(10);
}
catch(Exception e)
{

}
repaint();
}

}
}

直接运行代码即可看到效果