利用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(); }}