当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
计算机二级考试指导:一个Java小球撞击墙面的小程序
发布时间:2010/3/30 18:29:24 来源:城市学习网 编辑:admin

  一个Java小球撞击墙面的小程序
  import java.awt.*;
  import java.applet.*;
  public class OnlyChangeUpdate extends Applet implements Runnable
  {
  int X,Y,moveX,moveY,width,height;
  Thread newThread;
  public void init()
  {

  X=0;
  Y=0;
  moveX=20;
  moveY=20;
  width=getSize().width;
  height=getSize().height;
  setBackground(Color.black);
  }
  public void start()
  {
  newThread=new Thread(this);
  newThread.start();
  }
  public void stop()
  {
  newThread=null;
  }
  public void paint(Graphics g)
  {
  g.setColor(Color.white);
  g.fillOval(X,Y,15,15);
  }
  public void update(Graphics g)
  {
  paint(g);
  }
  public void run()
  {
  while(newThread !=null)
  {
  repaint();
  try
  {
  Thread.sleep(80);
  }
  catch(InterruptedException E){}
  X=X+moveX;
  Y=Y+moveY;
  if(X = (width - 15))
  {
  X=width-15;
  moveX=-moveX;
  }
  if(X=0)
  {
  X=0;
  moveX=-moveX;
  }
  if(Y=(height-15))
  {
  Y=height-15;
  moveY=-moveY+5;
  }
  if(Y=0)
  {
  Y=0;
  moveY=-moveY+5;
  }
  }
  }
  }
  关键是屏幕不能刷新,我已经认识到这点了
  后面讲到的双缓冲区可以解决的
  import java.awt.*;
  import java.applet.*;
  public class UseDoubleBuffering extends Applet implements Runnable
  {
  int X,Y,moveX,moveY,width,height;
  Thread newThread;
  Image OffScreen;
  Graphics drawOffscreen;
  public void init()
  {
  X=0;
  Y=0;
  moveX=2;
  moveY=3;
  width=getSize().width;
  height=getSize().height;
  OffScreen = createImage(width,height);
  drawOffscreen = OffScreen.getGraphics();
  }
  public void start()
  {
  newThread=new Thread(this);
  newThread.start();
  }
  public void stop()
  {
  newThread=null;
  }
  public void paint(Graphics g)
  {
  drawOffscreen.setColor(Color.black);
  drawOffscreen.fillRect(0,0,width,height);
  drawOffscreen.setColor(Color.white);
  drawOffscreen.fillOval(X,Y,15,15);
  g.drawImage(OffScreen,0,0,this);
  }
  public void update(Graphics g)
  {
  paint(g);
  }
  public void run()
  {
  while(newThread !=null)
  {
  repaint();
  try
  {
  Thread.sleep(50);
  }
  catch(InterruptedException E){}
  X=X+moveX;
  Y=Y+moveY;
  if(X = (width - 15))
  {
  X=width-15;
  moveX=-moveX;
  }
  if(X=0)
  {
  X=0;
  moveX=-moveX;
  }
  if(Y=(height-15))
  {
  Y=height-15;
  moveY=-moveY;
  }
  if(Y=0)
  {
  Y=0;
  moveY=-moveY;
  }
  }
  }
  }
  用这个双缓冲区 就解决了
  :

广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved