import menu.MenuListener; import menu.Item; import menu.Menu; import javax.microedition.lcdui.*; public class MenuCanvas extends Canvas implements MenuListener { private static final int ALERT_TIMEOUT = 4000; private static final String ALERT_TITLE = "Menu Example"; private static final int COLOR_BACKGROUND = 0xFFFFFF; private static final int COLOR_ITEM = 0x3B52D5; private static final int COLOR_ITEM_SELECTED = 0x0202CB; private static final Font font = Font.getDefaultFont(); private int w, h; private int firstItemPosition; private int fontHeight; private Menu mainMenu; private Item[] menuItems; private int itemIndex; public MenuCanvas() { setFullScreenMode(true); w = getWidth(); h = getHeight(); fontHeight = font.getHeight()+2; firstItemPosition = h/2 - h/4; mainMenu = new Menu(); mainMenu.addItem(new Item("mainMenu.addItem")); mainMenu.addItem(new Item("2mainMenu.addItem")); mainMenu.addItem(new Item("3mainMenu.addItem")); mainMenu.addItem(new Item("4mainMenu")); mainMenu.addItem(new Item("5mainMenu.addItem")); mainMenu.addItem(new Item("6mainMenu.addItem")); { public void itemAction (){ Main.midlet.destroyApp(true); } } mainMenu.setMenuListener(MenuCanvas.this); menuItems = mainMenu.getItems(); itemIndex = 0; } protected void paint(Graphics g) { g.setColor(COLOR_BACKGROUND); g.fillRect(0, 0, w, h); g.setFont(font); for(int i = 0; i < menuItems.length; i++) { String text = getItem(i).getLabel(); int color = COLOR_ITEM; if(i == itemIndex) { text = "<< "+text+" >>"; color = COLOR_ITEM_SELECTED; } g.setColor(color); g.drawString(text, w/2, firstItemPosition+i*fontHeight, Graphics.HCENTER | Graphics.TOP); } } protected void sizeChanged(int w, int h) { this.w = getWidth(); this.h = getHeight(); super.sizeChanged(w, h); } protected void keyPressed(int key) { int ga = getGameAction(key); switch(ga) { case UP: case LEFT: if(itemIndex < 0) itemIndex = menuItems.length - 1; break case DOWN: case RIGHT: itemIndex++; if(itemIndex >= menuItems.length) itemIndex = 0; break; case FIRE: mainMenu.action(itemIndex); break; } repaint(); } public void menuAction(int itemIndex) { Item currentItem = getItem(itemIndex); String itemLabel = currentItem.getLabel(); Alert showInfo = new Alert(ALERT_TITLE, itemLabel, null, AlertType.CONFIRMATION); showInfo.setTimeout(ALERT_TIMEOUT); Main.midlet.dsp.setCurrent(showInfo, this); currentItem.itemAction(); } private Item getItem(int itemIndex) { return menuItems[itemIndex]; } }