Java/J2ME/Key Event

Материал из Java эксперт
Версия от 18:01, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Canvas for processing game actions

/*--------------------------------------------------
* GameActions.java
*
* Canvas for processing game actions
*
* Example from the book:     Core J2ME Technology
* Copyright John W. Muchow   http://www.CoreJ2ME.ru
* You may use/modify for any non-commercial purpose
*-------------------------------------------------*/  
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class GameActions extends MIDlet
{
  private Display  display;       // The display
  private GameActionCanvas canvas;   // Canvas 
 
  public GameActions()
  {
    display = Display.getDisplay(this);
    canvas  = new GameActionCanvas(this);
  }
 
  protected void startApp()
  {
    display.setCurrent( canvas );
  }
 
  protected void pauseApp()
  { }
  protected void destroyApp( boolean unconditional )
  { }
 
  public void exitMIDlet()
  {
    destroyApp(true);
    notifyDestroyed();
  }
}
/*--------------------------------------------------
* GameActionCanvas.java
*
* Game action event handling
*-------------------------------------------------*/
class GameActionCanvas extends Canvas implements CommandListener
{
  private Command cmExit;          // Exit midlet
  private String keyText = null;    // Key code text
  private GameActions midlet;
  /*--------------------------------------------------
  * Constructor
  *-------------------------------------------------*/
  public GameActionCanvas(GameActions 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 key code 
  *-------------------------------------------------*/
  protected void paint(Graphics g)
  {
    // Clear the background (to white)
    g.setColor(255, 255, 255);
    g.fillRect(0, 0, getWidth(), getHeight());
    
    // Set color and draw text
    if (keyText != null)
    {
      // Draw with black pen
      g.setColor(0, 0, 0);
      // Center 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();
  }
  /*--------------------------------------------------
  * Game action event handling
  * A game action will be converted into a key code 
  * and handed off to this method
  *-------------------------------------------------*/  
  protected void keyPressed(int keyCode)
  {
    switch (getGameAction(keyCode))
    {
      // Place logic of each action inside the case
      case FIRE:
      case UP: 
      case DOWN:
      case LEFT:
      case RIGHT:
      case GAME_A:
      case GAME_B:
      case GAME_C:
      case GAME_D:
      default:
        // Print the text of the game action
        keyText = getKeyName(keyCode);
    }        
    repaint();
  }
}





Canvas for processing key code and commands

/*--------------------------------------------------
* KeyCodes.java
*
* Canvas for processing key code and commands
*
* Example from the book:     Core J2ME Technology
* Copyright John W. Muchow   http://www.CoreJ2ME.ru
* You may use/modify for any non-commercial purpose
*-------------------------------------------------*/  
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class KeyCodes extends MIDlet
{
  private Display  display;       // The display
  private KeyCodeCanvas canvas;   // Canvas 
 
  public KeyCodes()
  {
    display = Display.getDisplay(this);
    canvas  = new KeyCodeCanvas(this);
  }
 
  protected void startApp()
  {
    display.setCurrent( canvas );
  }
 
  protected void pauseApp()
  { }
  protected void destroyApp( boolean unconditional )
  { }
 
  public void exitMIDlet()
  {
    destroyApp(true);
    notifyDestroyed();
  }
}
/*--------------------------------------------------
* Class KeyCodeCanvas
*
* Key codes and commands for event handling
*-------------------------------------------------*/
class KeyCodeCanvas extends Canvas implements CommandListener
{
  private Command cmExit;          // Exit midlet
  private String keyText = null;    // Key code text
  private KeyCodes midlet;
  /*--------------------------------------------------
  * Constructor
  *-------------------------------------------------*/
  public KeyCodeCanvas(KeyCodes 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 key code 
  *-------------------------------------------------*/
  protected void paint(Graphics g)
  {
    // Clear the background (to white)
    g.setColor(255, 255, 255);
    g.fillRect(0, 0, getWidth(), getHeight());
    
    // Set color and draw text
    if (keyText != null)
    {
      // Draw with black pen
      g.setColor(0, 0, 0);
      // Close to the center      
      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();
  }
}





Event Example 1

/* License
 * 
 * Copyright 1994-2004 Sun Microsystems, Inc. All Rights Reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *  
 *  * Redistribution of source code must retain the above copyright notice,
 *      this list of conditions and the following disclaimer.
 * 
 *  * Redistribution in binary form must reproduce the above copyright notice,
 *      this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 * 
 * Neither the name of Sun Microsystems, Inc. or the names of contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *  
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *  
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility. 
 */
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class EventEx1 extends MIDlet implements CommandListener {
    // display manager
    Display display = null;
    
    // a menu with items
    List menu = null; // main menu
    // textbox
    TextBox input = null;
    // command
    static final Command backCommand = new Command("Back", Command.BACK, 0);
    static final Command mainMenuCommand = new Command("Main", Command.SCREEN, 1);
    static final Command exitCommand = new Command("Exit", Command.STOP, 2);
    String currentMenu = null;
    // constructor.
    public EventEx1() {
    }
    /**
     * Start the MIDlet by creating a list of items and associating the
     * exit command with it.
     */
    public void startApp() throws MIDletStateChangeException {
      display = Display.getDisplay(this);
      menu = new List("Menu Items", Choice.IMPLICIT);
      menu.append("Item1", null);
      menu.append("Item2", null);
      menu.append("Item3", null);
      menu.append("Item4", null);
      menu.addCommand(exitCommand);
      menu.setCommandListener(this);
      mainMenu();
    }
    public void pauseApp() {
      display = null;
      menu = null;
      input = null;
    }
    public void destroyApp(boolean unconditional) {
      notifyDestroyed();
    }
    // main menu
    void mainMenu() {
      display.setCurrent(menu);
      currentMenu = "Main"; 
    }
    /**
     * a generic method that will be called when selected any of
     * the items on the list.
     */
    public void prepare() {
       input = new TextBox("Enter some text: ", "", 5, TextField.ANY);
       input.addCommand(backCommand);
       input.setCommandListener(this);
       input.setString("");
       display.setCurrent(input);
    }
    /**
     * Test item1.
     */
    public void testItem1() {
      prepare();
      currentMenu = "item1";
    }
   
    /**
     * Test item2.
     */
    public void testItem2() {
       prepare();
       currentMenu = "item2"; 
    }
    /**
     * Test item3.
     */
    public void testItem3() {
       prepare();
       currentMenu = "item3"; 
    }
    /**
     * Test item4.
     */
    public void testItem4() {
       prepare();
       currentMenu = "item4"; 
    }

   /**
    * Handle events.
    */  
   public void commandAction(Command c, Displayable d) {
      String label = c.getLabel();
      if (label.equals("Exit")) {
         destroyApp(true);
      } else if (label.equals("Back")) {
          if(currentMenu.equals("item1") || currentMenu.equals("item2") ||
             currentMenu.equals("item3") || currentMenu.equals("item4"))  {
            // go back to menu
            mainMenu();
          } 
      } else {
         List down = (List)display.getCurrent();
         switch(down.getSelectedIndex()) {
           case 0: testItem1();break;
           case 1: testItem2();break;
           case 2: testItem3();break;
           case 3: testItem4();break;
         }
            
      }
  }
}





Event Example 2

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class EventEx2 extends MIDlet {
   Display display;
   public EventEx2() {
      display = Display.getDisplay(this);
   }
   public void destroyApp (boolean unconditional) {
      notifyDestroyed();
      System.out.println("App destroyed ");
   }
   public void pauseApp () {
      display = null;
      System.out.println("App paused.");
   }
   public void startApp () {
      Form form = new Form("Change Date");
        
      ItemStateListener listener = new ItemStateListener() {
         java.util.Calendar cal = 
           java.util.Calendar.getInstance(java.util.TimeZone.getDefault());
         public void itemStateChanged(Item item) {
            cal.setTime(((DateField)item).getDate());
            System.out.println("\nDate has changed");
         }
      };
      form.setItemStateListener(listener);
        
      java.util.Date now = new java.util.Date();
      DateField dateItem = new DateField("Today"s date:", DateField.DATE);
      dateItem.setDate(now);
      form.append(dateItem);
      display.setCurrent(form);
   }
}





Game Key Event

/*
J2ME in a Nutshell
By Kim Topley
ISBN: 0-596-00253-X
*/

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import javax.microedition.midlet.MIDlet;
public class EventsMIDlet extends MIDlet 
                        implements CommandListener {
    // The MIDlet"s Display object
    private Display display;
        
    // Flag indicating first call of startApp
    protected boolean started;
    
    // Exit command
    private Command exitCommand;
    
    protected void startApp() {
        if (!started) {
            display = Display.getDisplay(this);
            Canvas canvas = new EventsCanvas();            
            exitCommand = new Command("Exit", Command.EXIT, 0);
            canvas.addCommand(exitCommand);
            canvas.setCommandListener(this);
            display.setCurrent(canvas);
            
            started = true;
        }
    }
    protected void pauseApp() {
    }
    protected void destroyApp(boolean unconditional) {
    }
    public void commandAction(Command c, Displayable d) {
        if (c == exitCommand) {
            // Exit. No need to call destroyApp
            // because it is empty.
            notifyDestroyed();
        }
    }     
}
class EventsCanvas extends Canvas {
    
    static int[] keyCodes = {KEY_NUM0, KEY_NUM1, KEY_NUM2, KEY_NUM3, KEY_NUM4,
                             KEY_NUM5, KEY_NUM6, KEY_NUM7, KEY_NUM8, KEY_NUM9,
                             KEY_POUND, KEY_STAR};
    static String[] keyNames = {"KEY_NUM0", "KEY_NUM1", "KEY_NUM2", "KEY_NUM3", "KEY_NUM4",
                             "KEY_NUM5", "KEY_NUM6", "KEY_NUM7", "KEY_NUM8", "KEY_NUM9",
                             "KEY_POUND", "KEY_STAR"};
                             
    static int[] gameActions = {
                            UP, DOWN, LEFT, RIGHT, FIRE,
                            GAME_A, GAME_B, GAME_C, GAME_D};
    static String[] gameNames = {
                            "UP", "DOWN", "LEFT", "RIGHT", "FIRE",
                            "GAME_A", "GAME_B", "GAME_C", "GAME_D" };
    
    int lastKeyCode = 0;
    
    int lastX;
    
    int lastY;
    
    boolean pointer;
    protected void keyPressed(int keyCode) {
        lastKeyCode = keyCode;
        repaint();
    }
        
    protected void keyRepeated(int keyCode) {
        lastKeyCode = keyCode;
        repaint();
    }
        
    protected void keyReleased(int keyCode) {
        lastKeyCode = 0;
        repaint();
    }    
    protected void pointerPressed(int x, int y) {
        lastX = x;
        lastY = y;
        pointer = true;
        repaint();
    }
        
    protected void pointerDragged(int x, int y) {
        lastX = x;
        lastY = y;
        pointer = true;
        repaint();
    }
    
    protected void pointerReleased(int x, int y) {
        pointer = false;
        repaint();
    }
    
    protected void paint(Graphics g) {
        g.setColor(0xffffff);
        g.fillRect(0, 0, getWidth(), getHeight());
        
        g.setColor(0);
        if (lastKeyCode != 0) {
            String keyText = "keyCode " + lastKeyCode;
            String keyName = null;
            // See if it is a standard key
            for (int i = 0; i < keyCodes.length; i++) {
                if (lastKeyCode == keyCodes[i]) {
                    keyName = keyNames[i];
                    break;
                }
            }   
            
            if (keyName == null) {
                // See if it is a game action
                for (int i = 0; i < gameActions.length; i++) {
                    if (lastKeyCode == getKeyCode(gameActions[i])) {
                        keyName = gameNames[i];
                        break;
                    }
                }
            }
            
            g.drawString(keyText, getWidth()/2, getHeight()/2, 
                            Graphics.BASELINE|Graphics.HCENTER);
                    
            if (keyName != null) {
                g.drawString(keyName, getWidth()/2, getHeight()/2 + g.getFont().getHeight(), 
                            Graphics.BASELINE|Graphics.HCENTER);    
            }
        } else if (pointer) {
            g.drawString("(" + lastX + ", " + lastY + ")", getWidth()/2, getHeight()/2, 
                            Graphics.BASELINE|Graphics.HCENTER);
        }
    }
}





Key Event Demo

/*
 * @(#)Tiles.java 1.6 00/05/24 Copyright (c) 2000 Sun Microsystems, Inc. All
 * Rights Reserved.
 * 
 * This software is the confidential and proprietary information of Sun
 * Microsystems, Inc. ("Confidential Information"). You shall not disclose such
 * Confidential Information and shall use it only in accordance with the terms
 * of the license agreement you entered into with Sun.
 * 
 * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
 * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
 * NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
 * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES.
 */
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.midlet.MIDlet;
public class Tiles extends MIDlet {
  Board b;
  public Tiles() {
    b = new Board(this);
  }
  public void startApp() {
    Display.getDisplay(this).setCurrent(b);
  }
  public void pauseApp() {
  }
  public void destroyApp(boolean unconditional) {
  }
}
/*
 * @(#)Board.java 1.14 00/05/23 Copyright (c) 2000 Sun Microsystems, Inc. All
 * Rights Reserved.
 * 
 * This software is the confidential and proprietary information of Sun
 * Microsystems, Inc. ("Confidential Information"). You shall not disclose such
 * Confidential Information and shall use it only in accordance with the terms
 * of the license agreement you entered into with Sun.
 * 
 * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
 * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
 * NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
 * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES.
 */
class Board extends Canvas implements CommandListener {
  MIDlet midlet;
  Command exitCommand;
  Font font;
  // Character Position
  int xPos, yPos;
  // Chracter Height and Width in pixels
  int charW, charH;
  public Board(MIDlet midlet_) {
    int i;
    midlet = midlet_;
    Display dpy = Display.getDisplay(midlet);
    int letterWidth = 4;
    font = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN,
        Font.SIZE_MEDIUM);
    charW = font.charWidth("M") + 7;
    charH = font.getHeight() + 1;
    xPos = (getWidth() - (letterWidth * charW) + 1) / 2;
    yPos = 1;
    exitCommand = new Command("Exit", Command.SCREEN, 2);
    addCommand(exitCommand);
    setCommandListener(this);
    repaint();
  }
  public void commandAction(Command c, Displayable d) {
    if (c == exitCommand) {
      midlet.notifyDestroyed();
    }
  }
  public void paint(Graphics g) {
    g.setColor(0);
    g.drawRect(4, 4, 4 * charW + 2, 4 * charH + 2);
  }
  public void keyPressed(int code) {
    int game = getGameAction(code);
    switch (game) {
    case Canvas.UP:
      System.out.println("Canvas.UP");
      break;
    case Canvas.DOWN:
      System.out.println("Canvas.DOWN");
      break;
    case Canvas.LEFT:
      System.out.println("Canvas.LEFT");
      break;
    case Canvas.RIGHT:
      System.out.println("Canvas.RIGHT");
      break;
    }
    switch (code) {
    case Canvas.KEY_NUM0:
      System.out.println("Key 0");
      break;
    case Canvas.KEY_NUM1:
      System.out.println("Key 1");
      break;
    case Canvas.KEY_NUM2:
      System.out.println("Key 2");
      break;
    case Canvas.KEY_NUM3:
      System.out.println("Key 3");
      break;
    case Canvas.KEY_NUM4:
      System.out.println("Key 4");
      break;
    case Canvas.KEY_NUM5:
      System.out.println("Key 5");
      break;
    case Canvas.KEY_NUM6:
      System.out.println("Key 6");
      break;
    case Canvas.KEY_NUM7:
      System.out.println("Key 7");
      break;
    case Canvas.KEY_NUM8:
      System.out.println("Key 8");
      break;
    case Canvas.KEY_NUM9:
      System.out.println("Key 9");
      break;
    case Canvas.KEY_STAR:
      System.out.println("Star Key");
      break;
    case Canvas.KEY_POUND:
      System.out.println("Pound Key");
      break;
    //  default:
    //     System.out.println( "default" );
    //  return;
    }
  }
}





Key Event with Canvas

/* License
 * 
 * Copyright 1994-2004 Sun Microsystems, Inc. All Rights Reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *  
 *  * Redistribution of source code must retain the above copyright notice,
 *      this list of conditions and the following disclaimer.
 * 
 *  * Redistribution in binary form must reproduce the above copyright notice,
 *      this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 * 
 * Neither the name of Sun Microsystems, Inc. or the names of contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *  
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *  
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility. 
 */
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class EventEx3 extends MIDlet {
    Display display;
    Command exit;

    public EventEx3() {
        display = Display.getDisplay(this);
    }
    public void destroyApp (boolean unconditional) {
    }
    public void pauseApp () {
        System.out.println("App paused.");
    }
    public void startApp () {
       display = Display.getDisplay(this);
       Canvas canvas = new Canvas() { // anonymous class     
         public void paint(Graphics g) {
         }
         protected void keyPressed(int keyCode) {
           if (keyCode > 0) {
             System.out.println("keyPressed " +((char)keyCode));
           } else {
             System.out.println("keyPressed action " +getGameAction(keyCode));
           }                  
         }
         protected void keyReleased(int keyCode) {
           if (keyCode > 0) {
             System.out.println("keyReleased " +((char)keyCode));
           } else {
             System.out.println("keyReleased action " +getGameAction(keyCode));
           } 
         }
      }; // end of anonymous class
      exit = new Command("Exit", Command.STOP, 1);
      canvas.addCommand(exit);
      canvas.setCommandListener(new CommandListener() {
        public void commandAction(Command c, Displayable d) {
          if(c == exit) {
            notifyDestroyed();
          } else {
            System.out.println("Saw the command: "+c);
          }
        }
      });
      display.setCurrent(canvas);
    }
}





Key MIDlet

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.midlet.MIDlet;
public class KeyMIDlet extends MIDlet {
  public void startApp() {
    Displayable d = new KeyCanvas();
    d.addCommand(new Command("Exit", Command.EXIT, 0));
    d.setCommandListener(new CommandListener() {
      public void commandAction(Command c, Displayable s) {
        notifyDestroyed();
      }
    });
    Display.getDisplay(this).setCurrent(d);
  }
  public void pauseApp() {
  }
  public void destroyApp(boolean unconditional) {
  }
}
class KeyCanvas extends Canvas {
  private Font mFont = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_PLAIN, Font.SIZE_MEDIUM);
  private String mMessage = "[Press keys]";
  public KeyCanvas() {
  }
  public void paint(Graphics g) {
    int w = getWidth();
    int h = getHeight();
    g.setGrayScale(255);
    g.fillRect(0, 0, w - 1, h - 1);
    g.setGrayScale(0);
    g.drawRect(0, 0, w - 1, h - 1);
    g.setFont(mFont);
    int x = w / 2;
    int y = h / 2;
    g.drawString(mMessage, x, y, Graphics.BASELINE | Graphics.HCENTER);
  }
  protected void keyPressed(int keyCode) {
    int gameAction = getGameAction(keyCode);
    switch (gameAction) {
    case UP:
      mMessage = "UP";
      break;
    case DOWN:
      mMessage = "DOWN";
      break;
    case LEFT:
      mMessage = "LEFT";
      break;
    case RIGHT:
      mMessage = "RIGHT";
      break;
    case FIRE:
      mMessage = "FIRE";
      break;
    case GAME_A:
      mMessage = "GAME_A";
      break;
    case GAME_B:
      mMessage = "GAME_B";
      break;
    case GAME_C:
      mMessage = "GAME_C";
      break;
    case GAME_D:
      mMessage = "GAME_D";
      break;
    default:
      mMessage = "";
      break;
    }
    repaint();
  }
}





Low-Level Display Canvas:Key Code Example

/*
J2ME: The Complete Reference
James Keogh
Publisher: McGraw-Hill
ISBN 0072227109
*/
//jad file (please verify the jar size)
/*
MIDlet-Name: KeyCodeExample
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: KeyCodeExample.jar
MIDlet-1: KeyCodeExample, , KeyCodeExample
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100
*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class KeyCodeExample extends MIDlet
{
  private Display  display;       
  private MyCanvas canvas;   
  public KeyCodeExample ()
  {
    display = Display.getDisplay(this);
    canvas  = new MyCanvas(this);
  }
  protected void startApp()
  {
    display.setCurrent(canvas);
  }
  protected void pauseApp()
  { 
  }
  protected void destroyApp( boolean unconditional )
  { 
  }
  public void exitMIDlet()
  {
    destroyApp(true);
    notifyDestroyed();
  }
}
class MyCanvas extends Canvas implements CommandListener
{
  private Command exit;          
  private String direction;
  private KeyCodeExample keyCodeExample;
  public MyCanvas (KeyCodeExample keyCodeExample)
  {
    direction = "2=up 8=dn 4=lt 6=rt";    
    this.keyCodeExample = keyCodeExample;
    exit = new Command("Exit", Command.EXIT, 1);
    addCommand(exit);
    setCommandListener(this);
  } 
  protected void paint(Graphics graphics)
  {
    graphics.setColor(255,255,255);
    graphics.fillRect(0, 0, getWidth(), getHeight());
    graphics.setColor(255, 0, 0);
    graphics.drawString(direction, 0, 0, 
                         Graphics.TOP | Graphics.LEFT);
  }
  public void commandAction(Command command, Displayable displayable)
  {
    if (command == exit)
    {
      keyCodeExample.exitMIDlet();
     }
  }
  protected void keyPressed(int key)
  {
    switch ( key ){
     case KEY_NUM2:
       direction = "up";
       break;
     case KEY_NUM8:
       direction = "down";
       break;
     case KEY_NUM4:
       direction = "left";
       break;
     case KEY_NUM6:
       direction = "right";
       break;
    }
    repaint();
  }
}