的/*
* Canvaslet.Java
*
* Created on 2005年4月18日, 下午9:41
*/
import Javax.microedition.midlet.*;
import Javax.microedition.lcdui.*;
/**
*
* @author Administrator
* @version
*/
public class Canvaslet extends MIDlet implements CommandListener{
private Display aDisplay;
private MyCanvas myCanvas;
private Command okCommand;
private Command exitCommand;
private List aList;
private Font f;
public Canvaslet(){
okCommand=new Command("OK",Command.OK,1);
exitCommand=new Command("EXIT",Command.EXIT,1);
aList=new List("Font",Choice.EXCLUSIVE);
aList.append("Small",null);
aList.append("Medium",null);
aList.append("Large",null);
myCanvas=new MyCanvas();
aList.addCommand(okCommand);
aList.addCommand(exitCommand);
aList.setCommandListener(this);
}
public void startApp() {
aDisplay=Display.getDisplay(this);
aDisplay.setCurrent(aList);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d){
int i=aList.getSelectedIndex();
if(c==exitCommand){
destroyApp(false);
notifyDestroyed();
}
else if (c==okCommand);{
if(i==0){
myCanvas.setSize(Font.SIZE_SMALL);
}
else if (i==1){
myCanvas.setSize(Font.SIZE_MEDIUM);
}
else if (i==2){
myCanvas.setSize(Font.SIZE_LARGE);
}
aDisplay.setCurrent(myCanvas);
}
}
class MyCanvas extends Canvas implements CommandListener {
private Command exitcmd;
public MyCanvas(){
exitcmd=new Command("後退",Command.BACK,1);
addCommand(exitcmd);
setCommandListener(this);
}
private void setSize(int size){
f=Font.getFont(Font.FACE_SYSTEM,Font.STYLE_BOLD,size);
}
public void paint(Graphics g){
String s ="Hello";
g.setColor(0x00808080);
g.setFont(f);
g.drawString(s,getWidth()/2,getHeight()/2,Graphics.TOP|Graphics.LEFT);
g.drawLine(0,0,100,100);
}
public void commandAction(Command c ,Displayable d){
if(c==exitcmd){
aDisplay.setCurrent(aList);
}
}
}
}
這個程序的編寫過程很不順利,呵呵,畢竟是新手啊。
1.Font
對於Canvas中的字體,我以前一直不太熟悉。通過這次編程,我了解到,要得到一個字體對象,需要通過Font f = Font.getFont(int face, int style, int size)來得到。
2.含Canvas的MIDlet的一般寫法
先寫出MIDlet,然後再寫一個繼承自Canvas的內部類,在該類內部實現public void paint(Graphics g){}方法。在display時會自動調用paint方法。
3.在Canvas的子類中,可以使用Command和CommandListener接口,以實現後退等功能。