import java.util.random; import javax.microedition.lcdui.*; import javax.microedition.midlet.midlet; import javax.microedition.midlet.midletstatechangeexception; public class canvasdemo2 extends midlet { display display; mydrawingcanvas canvas; public canvasdemo2() { canvas = new mydrawingcanvas(this); } protected void destroyapp(boolean arg0) throws midletstatechangeexception { } protected void pauseapp() { } protected void startapp() throws midletstatechangeexception { display = display.getdisplay(this); display.setcurrent(canvas); canvas.repaint(); } } class mydrawingcanvas extends canvas implements commandlistener{ midlet mainmid; command ran,exit; int w,h; private command command; private graphics gh; static int count=0; mydrawingcanvas(midlet midlet) { w = this.getwidth(); h = this.getheight(); mainmid = midlet; ran = new command("swap",command.screen,1); exit = new command("exit",command.exit,1); this.addcommand(ran); this.addcommand(exit); this.setcommandlistener(this); } protected void paint(graphics gh) { count++; gh.setcolor(0); gh.fillrect(0, 0, w, h); int r,g,b,x,y,ws,hs; random ran = new random(); r = math.abs(ran.nextint()%255); g = math.abs(ran.nextint()%255);
b = math.abs(ran.nextint()%255); x = math.abs(ran.nextint()%w/2); y = math.abs(ran.nextint()%h/2); ws = math.abs(ran.nextint()%w/2); hs = math.abs(ran.nextint()%h/2); gh.setcolor(r,g,b); gh.fillrect(x, y, ws, hs); gh.drawstring(count+"", 0, h, graphics.bottom|graphics.left); } public void commandaction(command arg0, displayable arg1) { if(arg0==ran){ repaint(); } else if(arg0==exit){ mainmid.notifydestroyed(); } } }