//自动弹跳球
package text;
//弹跳球import java.awt.*;
import javax.swing.*;
public class MyTest {
public static void main(String[] args) {
JFrame a = new JFrame();
a.setSize(1026,765);
MyPanel mb = new MyPanel();
a.add(mb);
Thread t = new Thread(mb);
t.start();
a.setVisible(true);
}
}
class MyPanel extends JPanel implements Runnable {
int x = 30;
int y = 30;
int way = 0;
int i = 0;
public void paint(Graphics g) {
super.paint(g);
g.fillOval(x, y, 30, 30);
}
public void run() {
while (true) {
// 规定小球运行轨迹
if (way == 0) {
x++;
y++;
}
if (way == 1) {
x--;
y++;
}
if (way == 2) {
x--;
y--;
}
if (way == 3) {
x++;
y--;
}
// 规定小球反弹方式
if (x > 980) {
if (way == 0) {
way = 1;
} else {
way = 2;
}
}
if (y > 700) {
if (way == 1) {
way = 2;
} else {
way = 3;
}
}
if (x < 0) {
if (way == 2) {
way = 3;
} else {
way = 0;
}
}
if (y < 0) {
if (way == 3) {
way = 0;
} else {
way = 1;
}
}
try {
Thread.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
repaint();
}
}
}