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]); } } |