的/*
* 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接口,以实现后退等功能。