import java.io.*;

import javax.microedition.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class KeyCodeTest extends MIDlet
	implements CommandListener
{
	private Display mDisplay;
	private Command mExitCommand;
	private KeyCanvas mTextBox;

	public KeyCodeTest()
	{
		mExitCommand = new Command("Exit", Command.EXIT, 0);

		mTextBox = new KeyCanvas();
		mTextBox.addCommand(mExitCommand);
		mTextBox.setCommandListener(this);
	}


	public void commandAction(Command c, Displayable s)
	{
			try {Thread.sleep(2000);} catch (Exception e) {}
			destroyApp(false);
			notifyDestroyed();
			
	}

	public void startApp() {
	  mDisplay = Display.getDisplay(this);
	  mDisplay.setCurrent(mTextBox);
  }


  // implementing abstract methods:
  public void pauseApp() {}
  public void destroyApp(boolean unconditional) {}
}

class KeyCanvas
    extends Canvas {
  private Font mFont;
  private String mMessage = "[Press keys]";

  public KeyCanvas() {
    mFont = Font.getFont(Font.FACE_PROPORTIONAL,
        Font.STYLE_PLAIN, Font.SIZE_MEDIUM);
  }

  public void paint(Graphics g) {
    int w = getWidth();
    int h = getHeight();

    // Clear the Canvas.
    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);
    mMessage = ""+gameAction+": ";
    switch(gameAction) {
      case UP:     mMessage += "UP:  "+keyCode;             break;
      case DOWN:   mMessage += "DOWN:  "+keyCode;           break;
      case LEFT:   mMessage += "LEFT:  "+keyCode;           break;
      case RIGHT:  mMessage += "RIGHT:  "+keyCode;          break;
      case FIRE:   mMessage += "FIRE:  "+keyCode;           break;
      case GAME_A: mMessage += "GAME_A:  "+keyCode;         break;
      case GAME_B: mMessage += "GAME_B:  "+keyCode;         break;
      case GAME_C: mMessage += "GAME_C:  "+keyCode;         break;
      case GAME_D: mMessage += "GAME_D:  "+keyCode;         break;
      default:     mMessage += "Unknown: "+keyCode;               break;    }
    repaint();
  }
}

