1.2MIDP低级UI
与高级UI相比,低级UI就自由很多,任何时候我们可以调用repaint()产生重绘事件,调用完了repaint()会立刻返回,调用paint()回调函数则是由另一个专门的线程来完成。
相对于高级UI提供的丰富的组件,低级UI能够对
我们从javax.microedition.lcdui.Canvas开始了解我们的低级UI,我们要用到低级UI必须要继承Canvas这个抽象类,在 Canvas的核心是paint()这个方法,这个方法做是负责绘制屏幕上的画面,每当屏幕需要重新绘制时,就会产生重绘事件时,系统就会自动调用paint(),并传入一个Graphics对象。
任何时候我们都可以通过调用reapaint()方法来产生重绘事件,它有两个方法,一个需要四个参数,分别用来指示起始坐标(X,Y),长宽,另一个则不需要任何参数,代表整个画面重新绘制。
我们可以通过getWidth()和getHeight() 方法获得Canvas的当前范围大小。每当Canvas 范围大小发生变化时,就会自动调用Canvas类的 sizeChanged()方法。
下面是通用的用低级CANVAS API绘制九宫格程序的源码:
public class MenuCanvas extends Canvas implements CommandListener {
private String[] menuName = new String[] { "login", "picture", "wap",
"phone", "call", "goto", "fuck", "music", "video" };
private int canvaWidth = -1, canvaHeight = -1;
private int maxHeight = -1, imgWidth = -1, imgHeight = -1;
private int focus = 0;
private int fontHeight = -1;
private Image menuImg[] = new Image[9];
private Command exit;
public MenuCanvas() {
exit = new Command("Exit", Command.EXIT, 1);
addCommand(exit);
setCommandListener(this);
canvaWidth = getWidth();
canvaHeight = getHeight();
try {
for (int i = 0; i < menuImg.length; i++) {
menuImg[i] = Image.createImage(28, 28);
Graphics g = menuImg[i].getGraphics();
g.translate(-28 * i, 0);
}
} catch (Exception e) {
System.out.println(e.toString());
}
imgWidth = menuImg[0].getWidth();
imgHeight = menuImg[0].getHeight();
fontHeight = Font.getDefaultFont().getHeight();
maxHeight = imgHeight + fontHeight;
}
public void paint(Graphics g) {
int color = g.getColor();
g.setColor(0xFFFFFF);
g.fillRect(0, 0, canvaWidth, canvaHeight);
int cellWidth = canvaWidth / 3;
int cellHeight = canvaHeight / 3;
g.setColor(color);
for (int i = 0; i < menuImg.length; i++) {