?? viewcanvas.java
字號:
package com.j2medev.chapter3;
import java.io.IOException;
import javax.microedition.lcdui.*;
public class ViewCanvas extends Canvas implements CommandListener{
//用作圖標的圖片與標題
private Image[] menus = new Image[9];
private String[] titles = new String[]{"Login","Picture","Audio","Camera",
"WAP","Article","Help","Config","About"};
//標志焦點的位置,與titles的標簽對應
private int focus = 0;
//一系列的變量,用于計算相對位置適應不同的屏幕
private int canvasWidth = -1;
private int canvasHeight = -1;
private int margin = 1;//間距
private int maxHeight = -1;
private int imgHeight = -1;//圖標高度
private int imgWidth = -1;//圖標寬度
private Command exitCommand = new Command("Exit",Command.EXIT,1);
public ViewCanvas() {
addCommand(exitCommand);
setCommandListener(this);
//初始化圖片數組,將原始圖片分割為Image[]
try{
Image src = Image.createImage("/menus.png");
for(int i = 0;i<menus.length;i++){
menus[i] = Image.createImage(28,28);
Graphics g = menus[i].getGraphics();
g.translate(-28*i,0);
g.drawImage(src,0,0,Graphics.LEFT|Graphics.TOP);
}
src = null;//可以被回收
}catch(IOException ex){
ex.printStackTrace();
}
imgWidth = menus[0].getWidth();
imgHeight = menus[0].getHeight();
//默認字體的高度
int fontHeight = Font.getDefaultFont().getHeight();
canvasWidth = getWidth();
canvasHeight = getHeight();
maxHeight = margin+imgHeight+fontHeight;//圖片+標題的高度
}
public void paint(Graphics g){
//清除屏幕
int color = g.getColor();
g.setColor(0xFFFFFF);
g.fillRect(0,0,canvasWidth,canvasHeight);
g.setColor(color);
//計算每個單元格的高度和寬度
int cellWidth = canvasWidth/3;
int cellHeight = canvasHeight/3;
//繪制
for(int i = 0;i<menus.length;i++){
//繪制圖標
g.drawImage(menus[i],cellWidth*(i%3)+(cellWidth-imgWidth)/2,cellHeight*(i/3)+(cellHeight-maxHeight)/2,Graphics.LEFT|Graphics.TOP);
int _length = Font.getDefaultFont().stringWidth(titles[i]);
//繪制標題
g.drawString(titles[i],cellWidth*(i%3)+(cellWidth-_length)/2,cellHeight*(i/3)+(cellHeight-maxHeight)/2+imgHeight+margin,Graphics.LEFT|Graphics.TOP);
//繪制焦點
if(i == focus){
g.drawRect(cellWidth*(i%3),cellHeight*(i/3),cellWidth-margin,cellHeight-margin);
}
}
}
public void keyPressed(int keyCode){
//將鍵碼轉換為game action
int action = getGameAction(keyCode);
switch(action){
//響應用戶的確認事件
case FIRE:{
System.out.println(titles[focus]);
Alert alert = new Alert("you select",titles[focus],menus[focus],AlertType.INFO);
alert.setTimeout(2000);
IconViewMIDlet.setCurrent(alert);
break;
}
//根據用戶按下的方向鍵計算focus的變化
case UP:{
focus = focus - 3;
if(focus<0){
focus = focus + 9;
}
break;
}case DOWN:{
focus = focus + 3;
if(focus >= 9){
focus = focus - 9;
}
break;
}
case LEFT:{
if(focus <= 0){
focus = 8;
}else{
focus = (--focus)%9;
}
break;
}case RIGHT:{
focus = (++focus)%9;
break;
}
}
repaint();
serviceRepaints();
}
public void commandAction(Command cmd,Displayable displayable){
if(cmd == exitCommand){
IconViewMIDlet.exitMIDlet();
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -