在游戏开发中为了记录的用户积分,就需要用户输入自己的名字,这时就需要我们自己实现字母的输入。下面的代码演示了实现这个要求的方法。
/*
* MainCanvas.java
*
* Created on 2006年8月7日, 下午1:45
*
*/
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
/**
*
* @author mydeman
*/
public class MainCanvas extends Canvas{
//记录当前按了几次Fire键
private static int keyPressedCount = 0;
//当前显示的屏幕
private static int screenIndex = -1;
//定义字母表
private static final String[] ALPHABET = {
"A","B","C","D","E","F","G","H","I","J","K",
"L","M","N","O","P","Q","R","S","T","U","V",
"W","X","Y","Z"
};
/** Creates a new instance of MainCanvas */
public MainCanvas() {
setFullScreenMode(true);
}
//显示的字母的个数
private static int alphaNum = 0;
/**
* 根据屏幕索引,绘制屏幕
*/
protected void paint(Graphics g) {
switch(screenIndex) {
//绘制黑色背景
case -1 :
g.setColor(0, 0, 0);
g.fillRect(0, 0, getWidth(), getHeight());
break;
//绘制字母
case 1 :
//设置重绘的区域
g.setClip(30 + 15 * alphaNum, 100, 30 + 15 * (alphaNum + 1), 100);
g.setColor(0, 0, 0);
g.fillRect(30 + 15 * alphaNum, 100, 30 + 15 * (alphaNum + 1), 100);
//绘制字母
g.setColor(0, 255, 0);
g.drawString(ALPHABET[keyPressedCount], 30 + 15 * alphaNum, 100,
Graphics.TOP | Graphics.LEFT);
break;
}
}
/**
* 刷新屏幕
*/
private void refresh() {
repaint();
serviceRepaints();
}
private long old_time = 0;
/**
* 按键事件处理
*/
public void keyPressed(int keyCode) {
switch(getGameAction(keyCode)) {
case Canvas.FIRE :
//绘制的最大字母数为5个
if(alphaNum <= 5) {
//设置屏幕索引为1
screenIndex = 1;
//获得当前时间
long current = System.currentTimeMillis();
//如果当前时间和上次按键时间相差大于800ms,并且字母个数小于5个,
//则绘制下一个字母,同时将按键的次数设为0
if(current - old_time > 800 && alphaNum < 5) {
alphaNum ++;
keyPressedCount = 0;
} else {
//如果按键到了25次,也就是最后一个字母,则按键次数从0开始计数
keyPressedCount = (keyPressedCount == 25) ? 0 : (keyPressedCount + 1);
}
//保存当前按键时间
old_time = current;
//刷新屏幕
refresh();
}
break;
}
}
}