J2ME Key Codes Example

This application illustrates how to print the key value with the current key pressed on the canvas.

J2ME Key Codes Example

     

This application illustrates how to print the key value with the current key pressed on the canvas. In this application we are using the keyPressed method to repaint the key name according to its key code as below:

 

 

 

 

 

 

 

protected void keyPressed(int keyCode){   

  keyValue = getKeyName(keyCode);   

  repaint();   

}

The above method is created in the KeyCodeCanvas class, in which we inherited the canvas class to repaint the method.

The Application is as follows:

 

 

KeyCodesMIDlet.java

 

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class KeyCodesMIDlet extends MIDlet{
  private Display  display;
  private KeyCodeCanvas canvas;

  public KeyCodesMIDlet(){
  display = Display.getDisplay(this);
  canvas  = new KeyCodeCanvas(this);
  }

  protected void startApp(){
  display.setCurrent(canvas);
  }

  protected void pauseApp(){}

  protected void destroyAppboolean unconditional ){
  notifyDestroyed();
  }
}

class KeyCodeCanvas extends Canvas implements CommandListener{
  private Command exit;
  private String keyValue = null;
  private KeyCodesMIDlet midlet;

  public KeyCodeCanvas(KeyCodesMIDlet midlet){
  this.midlet = midlet;

  exit = new Command("Exit", Command.EXIT, 1);
  addCommand(exit);
  setCommandListener(this);
  

  protected void paint(Graphics g){
  g.setColor(25500);
  g.fillRect(00, getWidth(), getHeight());

  if (keyValue != null){
  g.setColor(00255);
  g.drawString(keyValue, getWidth()/2, getHeight()/2
   Graphics.TOP | Graphics.HCENTER
);
  }
  }

  public void commandAction(Command c, Displayable d){
  String label = c.getLabel();
  if(label.equals("Exit"))
  midlet.destroyApp(true);
  }

  protected void keyPressed(int keyCode){
  keyValue = getKeyName(keyCode);
  repaint();
  }
}

 

Download Source Code