Key Canvas : 2D « J2ME « Java






Key Canvas

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;

public 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);
    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();
  }
}



           
       








Related examples in the same category

1.Simple Midlet DemoSimple Midlet Demo
2.Piano MIDletPiano MIDlet
3.PacerPacer
4.Pointer ExamplePointer Example
5.Text Example
6.Simple Canvas
7.Illustrate Graphics MIDletIllustrate Graphics MIDlet
8.Translate CoordinatesTranslate Coordinates
9.Box Text CanvasBox Text Canvas
10.Offscreen MIDletOffscreen MIDlet
11.Quatsch MIDletQuatsch MIDlet
12.Sweep GameSweep Game
13.SweepSweep
14.Text MIDletText MIDlet
15.Translate coordinate systemTranslate coordinate system
16.Show various anchor pointsShow various anchor points
17.Draw mutable image on a canvas
18.Canvas for processing key code and commandsCanvas for processing key code and commands
19.Draw immutable image on a canvasDraw immutable image on a canvas
20.Use pointer events to draw onto the CanvasUse pointer events to draw onto the Canvas
21.A quick sample of graphics, commands, and event handling.A quick sample of graphics,  commands, and event handling.