九宫格菜单算法

package peng.canvas;

import javax.microedition.lcdui.*;

public class MenuCanvas extends Canvas implements CommandListener {
	private String[] menuName = new String[] { "login", "picture", "wap",
			"phone", "call", "goto", "fuck", "music", "video" };
	private int canvaWidth = -1, canvaHeight = -1;
	private int maxHeight = -1, imgWidth = -1, imgHeight = -1;
	private int focus = 0;
	private int fontHeight = -1;
	private Image menuImg[] = new Image[9];
	private Command exit;

	public MenuCanvas() {
		exit = new Command("Exit", Command.EXIT, 1);
		addCommand(exit);
		setCommandListener(this);
		canvaWidth = getWidth();
		canvaHeight = getHeight();
		try {
			for (int i = 0; i < menuImg.length; i++) {
				menuImg[i] = Image.createImage(28, 28);
				Graphics g = menuImg[i].getGraphics();
				g.translate(-28 * i, 0);
			}
		} catch (Exception e) {
			System.out.println(e.toString());
		}
		imgWidth = menuImg[0].getWidth();
		imgHeight = menuImg[0].getHeight();
		fontHeight = Font.getDefaultFont().getHeight();
		maxHeight = imgHeight + fontHeight;
	}

	public void paint(Graphics g) {
		int color = g.getColor();
		g.setColor(0xFFFFFF);
		g.fillRect(0, 0, canvaWidth, canvaHeight);
		int cellWidth = canvaWidth / 3;
		int cellHeight = canvaHeight / 3;
		g.setColor(color);
		for (int i = 0; i < menuImg.length; i++) {
			g.drawImage(menuImg[i], cellWidth * (i % 3)
					+ (cellWidth - imgWidth) / 2, cellHeight * (i / 3)
					+ (cellHeight - maxHeight) / 2, Graphics.TOP
					| Graphics.LEFT);
			int fontWidth = Font.getDefaultFont().stringWidth(menuName[i]);
			g.drawString(menuName[i], cellWidth * (i % 3)
					+ (cellWidth - fontWidth) / 2, cellHeight * (i / 3)
					+ (cellHeight - maxHeight) / 2 + imgHeight + 1,
					Graphics.TOP | Graphics.LEFT);
			if (i == focus) {
				g.drawRect(cellWidth * (i % 3) + (cellWidth - imgWidth) / 2,
						cellHeight * (i / 3) + (cellHeight - maxHeight) / 2,
						imgWidth + 1, imgHeight + 1);
			}
		}
	}

	public void keyPressed(int key) {
		int action = getGameAction(key);
		switch (action) {
		case FIRE:
			Alert alert = new Alert("You select:", menuName[focus],
					menuImg[focus], AlertType.INFO);
			alert.setTimeout(Alert.FOREVER);
			break;
		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 c, Displayable dpa) {
		if (c == exit) {
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值