利用thread解决paint()和用户输入响应同时将进行的问题。
public class mycanvas extends canvas implements runnable{ int r=0; public mycanvas() { thread t=new thread(this); t.start(); } public void run() { while(true) { r++; if(r>10) r=0; repaint(); } } public void paint(graphics g) { clear(g); paintanimation(g,100,10,r); } protected void keypressed(int keycode) { switch(getgameaction(keycode)) { case canvas.up: y=y-2; break; …… } }}
j2me已将stop()方法拿掉(j2se也不再提倡使用),我们利用标识(flag)来解决线程结束的问题boolean conti=false;……if(cmd.equals("停止")){ conti=false; removecommand(stop); addcommand(start);}else if(cmd.equals("开始")){ removecommand(start); addcommand(stop); conti=true; thread t=new thread(this); t.start();}……public void run(){ while(conti) { r++; if(r>10) r=0; repaint(); }}
时间控制不同机器处理速度不同,为了保持游戏,画面的一致性,通过时间控制流程来解决……int rate=50(50毫秒=1/20秒 画面重绘一次)public void run(){ long s1=0; long s2=0; long diff=0; while(conti) { s1=systen.currenttimemillis(); repaint(); servicerepaints(); s2=systen.currenttimemillis(); diff=s2-s1; system.out.rpintln(diff); if(diff<rate) { try { thread.sleep(rate-diff); }catch(exception exc){} } repaint(); }}
