📄 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 + -