主要演示在畫布中處理command的事件。
在MiracleCanvas中,通過他的構造函數把MiracleMIDlet的示例傳入,以便在command事件中控制退出。
import Javax.microedition.midlet.*;
import Javax.microedition.lcdui.*;
public class MiracleMIDlet extends MIDlet...{
Display display;
MiracleCanvas mCanvas;
public MiracleMIDlet()...{
if(mCanvas==null)...{
mCanvas = new MiracleCanvas(this);
}
}
public void startApp()...{
display = Display.getDisplay(this);
display.setCurrent(mCanvas);
}
public void pauseApp()...{
}
public void destroyApp(boolean uncondition)...{
}
}
import Javax.microedition.lcdui.*;
public class MiracleCanvas extends Canvas implements Runnable, CommandListener...{
MiracleMIDlet mMIDlet;
Thread t;
int width,height;
boolean draw=false;
private Command drawCommand = new Command("畫字",Command.OK, 1);
private Command exitCommand = new Command("退出", Command.EXIT,0);
public MiracleCanvas(MiracleMIDlet mMIDlet)...{
this.mMIDlet = mMIDlet;
width = getWidth();
height = getHeight();
setFullScreenMode(true);
addCommand(drawCommand);
addCommand(exitCommand);
setCommandListener(this);
t = new Thread(this);
t.start();
}
public void run()...{
while(true)...{
repaint();
try...{
Thread.sleep(500);
}catch(Exception e)...{
}
}
}
public void paint(Graphics g)...{
g.setColor(0);
g.fillRect(0,0,width,height);
g.setColor(-1);
g.drawString("Miracle", 64,64,20);
if(draw)...{
g.setColor(0xFF00FF);
g.drawString("drawing...", 64, 100,20);
}
}
public void commandAction(Command c, Displayable s)...{
if(c==drawCommand)...{
draw = !draw;
}
if(c==exitCommand)...{
mMIDlet.destroyApp(true);
mMIDlet.notifyDestroyed();
}
}
}