Home J2me J2ME Key Codes Example

Related Tutorials


 
 

Share on Google+Share on Google+

J2ME Key Codes Example

Advertisement
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

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 1, 2008

Related Tutorials

Discuss: J2ME Key Codes Example  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:1
iman arbabi
January 17, 2012
help for j2me programming

plz help me for How can I design a touch key for display an image on mobile screen?
DMCA.com