?? menucanvas.java
字號:
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);
}
//畫菜單選項,并根據(jù)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){
//根據(jù)用戶輸入更新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]);
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -