读书人

小球与线程小结

发布时间: 2013-08-04 18:26:16 作者: rapoo

小球与线程总结
public class BallThread extends Thread {public static final int LEFT = 1;public static final int RIGHT = 2;public static final int UP = 3;public static final int DOWN = 4;private int radius;private Color color;private int xSpeed;private int ySpeed;//球的当前位置private int x,y;//球的最后一次位置private int lastX,lastY;//球的水平方向的运动方向private int xDirection = RIGHT;//球的垂直方向的运动方向private int yDirection = DOWN;//暂停标识private boolean pauseFlag = false;//结束当前线程标记private boolean stopFlag = false;private JPanel jp;private Graphics g;public BallThread(JPanel jp) {this.jp = jp;g = jp.getGraphics();}public void setPause(boolean flag){this.pauseFlag = flag;}public void setStop(boolean flag){this.stopFlag = flag;}public void run() {init();while(true){try {sleep(100);} catch (InterruptedException e) {e.printStackTrace();}if(stopFlag == true){clear();return;}if(pauseFlag == true){continue;}clear();move();draw();}}private void init() {Random random = new Random();radius = 20+random.nextInt(30);color = new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256));xSpeed = 3+random.nextInt(8);ySpeed = 3+random.nextInt(8);}private void clear() {g.setColor(jp.getBackground());fillCircle(lastX,lastY,radius);}private void move() {if(x > jp.getWidth() - radius*2)this.xDirection = LEFT;if(x < 0)this.xDirection = RIGHT;if(y > jp.getHeight() - radius*2)this.yDirection = UP;if(y < 0)this.yDirection = DOWN;//保持上次的位置lastX = x;lastY = y;if(this.xDirection == LEFT)x -= this.xSpeed;if(this.xDirection == RIGHT)x += this.xSpeed;if(this.yDirection == UP)y -= this.ySpeed;if(this.yDirection == DOWN)y += this.ySpeed;}private void fillCircle(int x,int y,int r){g.fillOval(x-r, y-r, 2*r, 2*r);}private void draw() {g.setColor(color);fillCircle(x,y,radius);int red = color.getRed();int green = color.getGreen();int blue = color.getBlue();int r = this.radius;while(r > 4){r -= 2;red += 10;green += 10;blue += 10;if(red > 255) red = 255;if(green > 255) green = 255;if(blue > 255) blue = 255;Color c = new Color(red,green,blue);g.setColor(c);fillCircle(x,y,r);}}}

?学习了画图板、分形、数据结构、线程、文件I/O读写,现在是通信进行时,以前学习的知识仍旧存在很多漏洞,说起来我都想吐槽一下自己,你是有多懒啊多笨啊,一定要谨记自己是又笨又懒的人,一定要勤快,一定要在这个剩下的十几天里按部就班、兢兢业业地完成剩下的任务~否则我诅咒自己长呆毛~

读书人网 >编程

热点推荐