package com.j2medev.chapter3;
import javax.microedition.lcdui.*;
public class menucanvas extends canvas{
//selected变量标记了焦点位置
private int selected = 0;
private int preferwidth = -1;
private int preferheight = -1;
public static final int[] options = {0,1,2,3};
public static final string[] labels={"new game","setttings","high scores","exit"};
public menucanvas() {
selected = options[0];
//计算菜单选项的长度和高度值
font f = font.getdefaultfont();
for(int i = 0;i<labels.length;i++){
int temp = f.stringwidth(labels[i]);
if(temp > preferwidth){
preferwidth = temp;
}
}
preferwidth = preferwidth + 2*8;
preferheight = f.getheight()+2*4;
}
public void paint(graphics g){
//清除屏幕
int color = g.getcolor();
g.setcolor(0xffffff);
g.fillrect(0,0,getwidth(),getheight());
g.setcolor(color);
//计算整个菜单的高度,宽度和(x,y)
int rectwidth = preferwidth;
int rectheight = preferheight * labels.length;
int x = (getwidth()-rectwidth)/2;
int y = (getheight()-rectheight)/2;
//画矩形
g.drawrect(x,y,rectwidth,rectheight);
for(int i = 1;i<labels.length;i++){
g.drawline(x,y+preferheight*i,x+rectwidth,y+preferheight*i);
}
//画菜单选项,并根据selected的值判断焦点
for(int j = 0;j<labels.length;j++){
if(selected == j){
g.setcolor(0x6699cc);
g.fillrect(x+1,y+j*preferheight+1,rectwidth-1,preferheight-1);
g.setcolor(color);
}
g.drawstring(labels[j],x+8,y+j*preferheight+4,graphics.left|graphics.top);
}
}
public void keypressed(int keycode){
//根据用户输入更新selected的值,并重新绘制屏幕
int action = this.getgameaction(keycode);
switch(action){
case canvas.fire:
printlabel(selected);
break;
case canvas.down:
selected = (selected+1)%4;
break;
case canvas.up:{
if(--selected < 0){
selected+=4;
}
break;
}
default:
break;
}
repaint();
servicerepaints();
}
//shownotify()在paint()之前被调用
public void shownotify(){
system.out.println("shownotify() is called");
}
private void printlabel(int selected){
system.out.println(labels[selected]);
}
}
|