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

单一线程中flushGraphics的问题
下面的代码是让屏幕每隔1秒显示一种颜色。

public class MyTest extends MIDlet {
Display d = null;
public MyTest() {
d = Display.getDisplay(this);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
}
protected void pauseApp() {

}

protected void startApp() throws MIDletStateChangeException {
// TODO Auto-generated method stub
WinCanvas w = new WinCanvas(false);
d.setCurrent(w);
//w.myPaint();这里也是可以运行成功的
}

public class WinCanvas extends GameCanvas implements Runnable {

private Graphics g;
int color[] = {0x112233,0xabcd12,0x23dffa,0x12acda,0x7641af,0x9812af,0xbbaf12};
public WinCanvas(boolean arg0) {
super(arg0);
g = this.getGraphics();
g.setColor(0x000000);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
}

public synchronized void myPaint(){
for(int i=0;i<color.length;i++){
g.setColor(color[i]);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
this.flushGraphics();
System.out.println("ok");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
}

public void keyPressed(int k){
k = this.getKeyStates();
if((k&GameCanvas.FIRE_PRESSED)!=0) this.myPaint();//这里调用则只是显示最后的一个颜色
  if((k&GameCanvas.LEFT_PRESSED)!=0) new Thread(this).start();//这样可以 }
public void run() {
myPaint();//新开线程运行,显示正常。
}
}


我想问的,为什么会出现这样的现象,什么原理。另外eclipse的wireless Toolkit2.5.2是可以的。可以一到真机就不行了。

------解决方案--------------------
for(int i=0;i <color.length;i++){
g.setColor(color[i]);
g.fillRect(0, 0, this.getWidth(), this.getHeight());

-_-!!
逻辑错误吧。
你来个循环不停的赋值颜色然后画图,是画的太快了你看不到那颜色变化所以只停留到最后一种颜色,应该用另外一种循环,根据外部条件每paint一次只赋值颜色画图一次,你试试看。
int c = 0;//外部定义

if(c>color.length-1)c=0;
g.setColor(color[c]);
c+=1;
g.fillRect(0, 0, this.getWidth(), this.getHeight());