// 碰撞的小球
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class BallTest2 extends MIDlet implements CommandListener {
Display display; // 设备的显示器
BallCanvas canvas; // 用于显示小球的屏幕
private Command exitCommand = new Command( "Exit ", Command.EXIT, 1); //退出命令
public BallTest2() {
display = Display.getDisplay(this); //取得设备的显示器
canvas = new BallCanvas(display); // 实例化canvas对象
canvas.addCommand(exitCommand); // 为canvas加上退出命令
canvas.setCommandListener(this); // 为canvas设置命令监听者
}
// 重载抽象类MIDlet的抽象方法startApp()
public void startApp() {
canvas.start();
}
// 重载抽象类MIDlet的方法destroyApp()
public void destroyApp(boolean bl) {
canvas.destroy();
}
// 重载抽象类MIDlet的方法pauseApp()
public void pauseApp(){}
// 实现接口CommandListener的方法
public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(false); // 销毁程序
notifyDestroyed(); // 通知销毁程序
}
}
public class BallCanvas extends Canvas implements Runnable{
// java.util.Random random = new java.util.Random();
int posX=5, posY=5; //小球显示位置
int ballSize = 10; //小球尺寸
Display display; //显示器
public BallCanvas(Display display){ //构造函数
//super();
this.display=display;
}
public void run() { //线程的主方法
while (true){
this.posX = 20;//(random.nextInt()> > > 1) % (this.getWidth()-20) + 10; //生成小球位置X坐标
this.posY = 50;//(random.nextInt()> > > 1) % (this.getHeight()-20) + 10; //生成Y坐标
try {
Thread.sleep(100); //线程休眠
} catch (InterruptedException e) {}