日期:2014-05-20  浏览次数:20681 次

一个随机移动的小球怎么让它从上到下移动
完整程序如下:

自己写的随机移动的小球
import   javax.microedition.midlet.MIDlet;
import   javax.microedition.lcdui.*;
import   java.util.*;
import   javax.microedition.midlet.MIDletStateChangeException;


public   class   BallTest5   extends   MIDlet   implements   CommandListener   {
private   Display   display;
private   Command   cmdExit;
private   Ball   ball;
public   BallTest5()   {
//   TODO   自动生成构造函数存根
display=Display.getDisplay(this);
ball=new   Ball(display);
cmdExit=new   Command( "退出 ",Command.SCREEN,1);
ball.addCommand(cmdExit);
ball.setCommandListener(this);
}

protected   void   destroyApp(boolean   arg0)   throws   MIDletStateChangeException   {
//   TODO   自动生成方法存根

}

protected   void   pauseApp()   {
//   TODO   自动生成方法存根

}

protected   void   startApp()   throws   MIDletStateChangeException   {
//   TODO   自动生成方法存根
ball.start();

}
public   void   commandAction(Command   c,Displayable   d)
{
if(c==cmdExit)
{
notifyDestroyed();
}
}


public   class   Ball   extends   Canvas   implements   Runnable{
Random   random=new   Random();
int   posX=20;
int   posY=20;
int   ballsize=60;
Display   display;

public   Ball(Display   display)
{
super();
this.display=display;
}


public   void   run()
{
while(true)
{
this.posX=(random.nextInt()> > > 1)%(this.getWidth()-20)+10;
this.posY=(random.nextInt()> > > 1)%(this.getHeight()-20)+10;
try{
Thread.sleep(2000);
}
catch(Exception   e)
{
e.printStackTrace();
}
repaint();
}
}

public   void   start()
{
display.setCurrent(this);
Thread   t=new   Thread(this);
t.start();
repaint();
}

protected   void   paint(Graphics   g)
{
int   x=g.getClipX();
int   y=g.getClipY();
int   width=g.getClipWidth();
int   height=g.getClipHeight();
g.setColor(230);
g.fillRect(x,   y,   width,   height);
g.setColor(10);
g.fillArc(posX,   posY,   ballsize,   ballsize,   0,   360);
}
}

}


------解决方案--------------------
public void run()
{
while(true)
{
this.posY -= 20;
if(this.posY > getHeight() - 10) [
posY = 10;
}
try{
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
repaint();
}
}