// Copyright (c) 2007, Mihai Preda. // Licensed under the MIT License. import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.List; import javax.microedition.midlet.MIDlet; class Menu extends Cmd implements CommandListener { static Command cmdBack = new Command("Back", Command.BACK, 2); static void setBackText(String backText) { cmdBack = new Command(backText, Command.BACK, 200); } Menu(String label, Command children[]) { this(label, children, 0); } Menu(String label, Command children[], int selectedIndex) { super(label, -1); this.children = children; int nChildren = children.length; String childLabels[] = new String[nChildren]; for (int i = 0; i < nChildren; ++i) { childLabels[i] = children[i].getLabel(); } list = new List(label, List.IMPLICIT, childLabels, null); if (selectedIndex >= 0 && selectedIndex < nChildren) { list.setSelectedIndex(selectedIndex, true); } list.addCommand(cmdBack); list.setCommandListener(this); } void addCommandsTo(Displayable d) { for (int i = 0; i < children.length; ++i) { d.addCommand(children[i]); } d.setCommandListener(this); } void setParent(MIDlet midlet, Displayable parent) { this.midlet = midlet; this.parent = parent; int nChildren = children.length; for (int i = 0; i < nChildren; ++i) { if (children[i] instanceof Menu) { ((Menu)children[i]).setParent(midlet, list); } } } public void commandAction(Command cmd, Displayable cmdSource) { if (display == null) { display = Display.getDisplay(midlet); } if (cmd.getCommandType() == Command.BACK) { Log.log("back to " + parent); display.setCurrent(parent); return; } //int index = ((List)cmdSource).getSelectedIndex(); Command child = (cmdSource==list)?children[list.getSelectedIndex()]:cmd; Log.log("cmd " + cmd + " child " + child + " source " + cmdSource); if (child instanceof Menu) { display.setCurrent(((Menu)child).list); } else { ((CommandListener)midlet).commandAction(child, parent); } } Command[] children; List list; Displayable parent; MIDlet midlet; Display display; }