//by sword2008@程序之巢
//网上的那些错误基本上改正
import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.*;
public class menucanvas extends MIDlet
{ public menucanvas(){}
public void startApp(){
Display.getDisplay(this).setCurrent(new Can());}
public void pauseApp(){}
public void destroyApp(boolean unkowmn){}
}
class Can extends Canvas{
//焦点
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={"新游戏","设置","高分","退出"};
public Can(){
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*16;
preferheight = f.getHeight()+2*8;
}
}
//paint
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);
}
//
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(){//90
System.out.println("shownotify() is called");
}
private void printlabel(int selected){
System.out.println(labels[selected]);
}
}
/*
int action = getGameAction(keyCode);
其中,keyCode和游戏动作的对应关系如下:
Canvas.UP——数字键2和向上导航键
Canvas.DOWN——数字键8和向下导航键
Canvas.LEFT——数字键4和向左导航键
Canvas.RIGHT——数字键6和向右导航键
Canvas.FIRE——数字键5和确定导航键
Game_A、Game_B、Game_C、Game_D分别对应键盘上的1、3、7、9或者是7、9、*、#键。
经过上面的转换以后,代码实现就和手机键盘上的键值无关了。
另外,如果是Nokia系列的手机,还可以使用com.nokia.mid.ui.FullCanvas类里面的SOFTKEY1、SOFTKEY2来控制Nokia系列手机上的左右两个软键,做到这两个软键的处理通用。
*/
评论