package BallDemo;
import java.awt.Color;
import javax.swing.JFrame;
public class BallMain {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setBounds(50, 50, 400, 400);
panel panel = new panel(frame);//新建画板,把窗体参数传入,因为panel里需要窗体大小
panel.setBackground(Color.black);
frame.add(panel);//把画板增加到窗体上
frame.setTitle("单球");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//默认关闭操作。
frame.setVisible(true);
Thread t1 = new Thread(panel);
t1.run();
}
}
package BallDemo;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
class panel extends JPanel implements Runnable {
JFrame f;
public panel(JFrame f) {
this.f = f;
}
//初始化值,把小球方向初始为随机方向,
private int x = 100;
private int y = 0;
private int count = new Random().nextInt(3) + 1;
Random random = new Random();
@Override
public void run() {
while (true) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//小球方向控制,通过x y 的自增自减实现
switch (count) {
case 1:
x++;
y++;
if (x > f.getWidth() - 60) {
count = 2;
} else if (y > f.getHeight() - 90) {
count = 4;
}
break;
case 2:
x--;
y++;
if (x < 0) {
count = 1;
} else if (y > f.getHeight() - 90) {
count = 3;
}
break;
case 3:
x--;
y--;
if (x < 0) {
count = 4;
} else if (y < 0) {
count = 2;
}
break;
case 4:
x++;
y--;
if (x > f.getWidth() - 60) {
count = 3;
} else if (y < 0) {
count = 1;
}
break;
}
repaint();
}
}
public void paint(Graphics g) {
// TODO Auto-generated method stub
super.paint(g);
g.setColor(Color.red);
g.fillOval(x, y, 50, 50);
}
}
|