// Application for processing key code on canvas import javax.microedition.lcdui.*; import javax.microedition.midlet.*; public class PrintKeyCode extends MIDlet { private Display display; private KeyCodeCanvas canvas; // reference to a canvas // constructor public PrintKeyCode(){ display = Display.getDisplay(this); canvas = new KeyCodeCanvas(this); } // startApp protected void startApp(){ display.setCurrent(canvas); } // pauseApp protected void pauseApp(){ } // destroyApp protected void destroyApp(boolean unconditional){ } public void exitMIDlet(){ destroyApp(true); notifyDestroyed(); } } /* Class PrintKeyCanvas - Key codes & commands for event handling */ class KeyCodeCanvas extends Canvas implements CommandListener{ private Command cmExit; private String keyText = null; private PrintKeyCode midlet; // Constructor public KeyCodeCanvas(PrintKeyCode midlet){ this.midlet = midlet; // create exit command & Listen for events cmExit = new Command("Exit", Command.EXIT, 1); addCommand(cmExit); setCommandListener(this); } // paint the text representing the keycode // The Graphics object is used to render directly onto the Canvas protected void paint(Graphics g){ // Clear the background i.e. clear the display g.setColor(255,255,255); // white g.fillRect(0, 0, getWidth(), getHeight()); System.out.println("Graphics area is:" +getWidth() + ","+getHeight()); // set colour and draw text if(keyText != null){ // draw with black pen g.setColor(0,0,0); // centre the text g.drawString(keyText, getWidth()/2, getHeight()/2, Graphics.TOP | Graphics.HCENTER); } } /* Command event handling */ public void commandAction(Command c, Displayable d){ if (c == cmExit) midlet.exitMIDlet(); } /* Key code event handling */ protected void keyPressed(int KeyCode){ keyText = getKeyName(KeyCode); repaint(); } }