Canvas key event and navigate through arrow keys : Canvas « J2ME « Java Tutorial






import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.midlet.MIDlet;

public class Navigate2MIDlet extends MIDlet implements CommandListener {

  private Command exitCommand;

  Displayable nd;

  Image image = null;

  public Navigate2MIDlet() {
    try {
      image = Image.createImage("/J.png");
    } catch (Exception e) {
    }

    Display display = Display.getDisplay(this);

    nd = new Navigate2Canvas(image);

    exitCommand = new Command("exit", Command.EXIT, 1);

    nd.addCommand(exitCommand);

    nd.setCommandListener(this);
    display.setCurrent(nd);
  }

  public void startApp() {
  }

  public void pauseApp() {
  }

  public void destroyApp(boolean unconditional) {
  }

  public void commandAction(Command c, Displayable s) {
    notifyDestroyed();
  }
}

class Navigate2Canvas extends Canvas {
  private Image image;

  private int newX = 0;

  private int newY = 0;

  private int stepX = 0;

  private int stepY = 0;

  public Navigate2Canvas(Image image) {
    this.image = image;
    newX = 0;
    newY = 0;
    stepX = getWidth() / 4;
    stepY = getHeight() / 4;
  }

  public void steppingXY(int x, int y) {
    newX += x;
    newY += y;
  }

  public void paint(Graphics g) {
    int width = this.getWidth();
    int height = this.getHeight();

    g.setGrayScale(255);
    g.fillRect(0, 0, width - 1, height - 1);
    g.setGrayScale(0);
    g.drawRect(0, 0, width - 1, height - 1);

    g.translate(newX, newY);
    g.drawImage(image, 0, 0, g.TOP | g.LEFT);
  }

  protected void keyPressed(int keyCode) {
    int gameaction = getGameAction(keyCode);
    switch (gameaction) {
    case UP:
      steppingXY(0, stepY);
      break;
    case DOWN:
      steppingXY(0, -stepY);
      break;
    case LEFT:
      steppingXY(stepX, 0);
      break;
    case RIGHT:
      steppingXY(-stepX, 0);
      break;
    }
    repaint();
  }
}








31.24.Canvas
31.24.1.extends Canvas to create your own drawable areaextends Canvas to create your own drawable area
31.24.2.Get Canvas propertiesGet Canvas properties
31.24.3.Canvas key pressed and key typed events
31.24.4.Use Canvas to draw a clockUse Canvas to draw a clock
31.24.5.Canvas sizeCanvas size
31.24.6.Navigatable Canvas
31.24.7.Canvas key event and navigate through arrow keys