Java/J2ME/2D — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 06:37, 1 июня 2010

Box Text Canvas

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
public class BoxTextCanvas extends Canvas {
  private Font mFont;
  public BoxTextCanvas() {
    mFont = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_PLAIN, Font.SIZE_LARGE);
  }
  public void paint(Graphics g) {
    int w = getWidth();
    int h = getHeight();
    g.setColor(0xffffff);
    g.fillRect(0, 0, w, h);
    g.setColor(0x000000);
    String s = "dolce";
    int stringWidth = mFont.stringWidth(s);
    int stringHeight = mFont.getHeight();
    int x = (w - stringWidth) / 2;
    int y = h / 2;
    g.setFont(mFont);
    g.drawString(s, x, y, Graphics.TOP | Graphics.LEFT);
    g.drawRect(x, y, stringWidth, stringHeight);
  }
}





Illustrate Graphics MIDlet

/*
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.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.List;
import javax.microedition.midlet.MIDlet;
public class GraphicsMIDlet 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;
    
    // Back to examples list command
    private Command backCommand;
    
    // The example selection list
    private List examplesList;
    
    // The Canvases used to demonstrate different Items
    private Canvas[] canvases;
    
    // The example names. Used to populate the list.
    private String[] examples = {
        "Lines", "Rectangles", "RectangleFills",
        "Arcs", "FilledArcs", "Text"
    };
    protected void startApp() {
        if (!started) {
            started = true;
            display = Display.getDisplay(this);
            
            // Create the common commands
            createCommands();
            
            // Create the canvases
            createCanvases();
            
            // Create the list of examples
            createList();
            
            // Start with the List
            display.setCurrent(examplesList);
        }
    }
    protected void pauseApp() {
    }
    protected void destroyApp(boolean unconditional) {
    }
    public void commandAction(Command c, Displayable d) {
        if (d == examplesList) {
            // New example selected
            int index = examplesList.getSelectedIndex();
            display.setCurrent(canvases[index]);
        } else if (c == exitCommand) {
            // Exit. No need to call destroyApp
            // because it is empty.
            notifyDestroyed();
        } else if (c == backCommand) {
            // Go back to main selection list
            display.setCurrent(examplesList);
        }
    }
    
    private void createCommands() {
        exitCommand = new Command("Exit", Command.EXIT, 0);
        backCommand = new Command("Back", Command.BACK, 1);
    }
    
    private void createList() {
        examplesList = new List("Select Example", List.IMPLICIT);
        for (int i = 0; i < examples.length; i++) {
            examplesList.append(examples[i], null);
        } 
        examplesList.setCommandListener(this);
    }
    
    private void createCanvases() {
        canvases = new Canvas[examples.length];
        canvases[0] = createLinesCanvas();
        canvases[1] = createRectanglesCanvas();
        canvases[2] = createRectangleFillsCanvas();
        canvases[3] = createArcsCanvas();
        canvases[4] = createFilledArcsCanvas();
        canvases[5] = createTextCanvas();
        
    }
    private void addCommands(Displayable d) {
        d.addCommand(exitCommand);
        d.addCommand(backCommand);
        d.setCommandListener(this);
    }
    
    // Create the Canvas for the line drawing example
    private Canvas createLinesCanvas() {
        Canvas canvas = new LineCanvas();        
        addCommands(canvas);
        return canvas;
    }    
        
    // Create the Canvas for the rectangles example
    private Canvas createRectanglesCanvas() {
        Canvas canvas = new RectanglesCanvas();        
        addCommands(canvas);
        return canvas;
    }
        
    // Create the Canvas for the filled rectangles example
    private Canvas createRectangleFillsCanvas() {
        Canvas canvas = new RectangleFillsCanvas();        
        addCommands(canvas);
        return canvas;
    }
        
    // Create the Canvas for the arcs example
    private Canvas createArcsCanvas() {
        Canvas canvas = new ArcsCanvas();        
        addCommands(canvas);
        return canvas;
    }
           
    // Create the Canvas for the filled arcs example
    private Canvas createFilledArcsCanvas() {
        Canvas canvas = new FilledArcsCanvas();        
        addCommands(canvas);
        return canvas;
    }    
               
    // Create the Canvas for the text example
    private Canvas createTextCanvas() {
        Canvas canvas = new TextCanvas();        
        addCommands(canvas);
        return canvas;
    }
}
// A canvas that illustrates line drawing
class LineCanvas extends Canvas {
    public void paint(Graphics g) {
        int width = getWidth();
        int height = getHeight();
        // Fill the background using black
        g.setColor(0);
        g.fillRect(0, 0, width, height);
        // White horizontal line
        g.setColor(0xFFFFFF);
        g.drawLine(0, height/2, width - 1, height/2);
        // Yellow dotted horizontal line
        g.setStrokeStyle(Graphics.DOTTED);
        g.setColor(0xFFFF00);
        g.drawLine(0, height/4, width - 1, height/4);
        // Solid diagonal line in brightest gray
        g.setGrayScale(255);
        g.setStrokeStyle(Graphics.SOLID);
        g.drawLine(0, 0, width - 1, height - 1);
    }    
}
// A canvas that illustrates rectangles
class RectanglesCanvas extends Canvas {
    public void paint(Graphics g) {
        int width = getWidth();
        int height = getHeight();
        // Create a white background
        g.setColor(0xffffff);
        g.fillRect(0, 0, width, height);
        
        // Draw a solid rectangle
        g.setColor(0);
        g.drawRect(width/4, 0, width/2, height/4);
                
        // Draw a dotted rectangle inside
        // the solid rectangle.
        g.setStrokeStyle(Graphics.DOTTED);
        g.drawRect(width/4 + 4, 4, width/2 - 8, height/4 - 8);
        
        // Draw a rounded rectangle
        g.setStrokeStyle(Graphics.SOLID);
        g.drawRoundRect(width/4, height/2, width/2, height/4, 16, 8);
    }
}
// A canvas that illustrates filled rectangles
class RectangleFillsCanvas extends Canvas {
    public void paint(Graphics g) {
        int width = getWidth();
        int height = getHeight();
        // Create a black background
        g.setColor(0);
        g.fillRect(0, 0, width, height);
        // Draw a filled rectangle with
        // a dotted rectangle around it
        g.setStrokeStyle(Graphics.DOTTED);
        g.setColor(0x00ff00);
        g.fillRect(width/4, height/4, width/2, height/2);
        g.setColor(0xffff00);
        g.drawRect(width/4, height/4, width/2, height/2);
    }
}
// A canvas that illustrates arcs
class ArcsCanvas extends Canvas {
    public void paint(Graphics g) {
        int width = getWidth();
        int height = getHeight();
        // Create a black background
        g.setColor(0);
        g.fillRect(0, 0, width, height);
        // A quarter circle, clockwise 90 degrees
        // from the 3 o"clock position. Show the
        // bounding rectangle as well.
        g.setColor(0xffffff);
        g.drawArc(0, 0, width/2, height/2, 0, 90);
        g.setStrokeStyle(Graphics.DOTTED);
        g.setColor(0xffff00);
        g.drawRect(0, 0, width/2, height/2);
        // A quarter circle, anticlockwise 90 degrees
        // from the 3 o"clock position. 
        g.setStrokeStyle(Graphics.SOLID);
        g.setColor(0xffffff);
        g.drawArc(width/2, 0, width/2, height/2, 0, -90);
        g.setStrokeStyle(Graphics.DOTTED);
        g.setColor(0xffff00);
        g.drawRect(width/2, 0, width/2, height/2);
       
        // An elliptical arc from the six o"clock
        // position, counterclockwise 180 degrees
        g.setStrokeStyle(Graphics.SOLID);
        g.setColor(0xffffff);
        g.drawArc(0, height/2, width, height/2, -90, -180);
        g.setStrokeStyle(Graphics.DOTTED);
        g.setColor(0xffff00);
        g.drawRect(0, height/2, width, height/2);        
    }
}
// A canvas that illustrates filled arcs
class FilledArcsCanvas extends Canvas {
    public void paint(Graphics g) {
        int width = getWidth();
        int height = getHeight();
        // Create a black background
        g.setColor(0);
        g.fillRect(0, 0, width, height);
        // A quarter circle, clockwise 90 degrees
        // from the 3 o"clock position. Show the
        // bounding rectangle as well.
        g.setColor(0xffffff);
        g.fillArc(0, 0, width/2, height/2, 0, 90);
        g.setStrokeStyle(Graphics.DOTTED);
        g.setColor(0xffff00);
        g.drawRect(0, 0, width/2, height/2);
        // A quarter circle, anticlockwise 90 degrees
        // from the 3 o"clock position. 
        g.setStrokeStyle(Graphics.SOLID);
        g.setColor(0xffffff);
        g.fillArc(width/2, 0, width/2, height/2, 0, -90);
        g.setStrokeStyle(Graphics.DOTTED);
        g.setColor(0xffff00);
        g.drawRect(width/2, 0, width/2, height/2);
       
        // An elliptical arc from the six o"clock
        // position, counterclockwise 180 degrees
        g.setStrokeStyle(Graphics.SOLID);
        g.setColor(0xffffff);
        g.fillArc(0, height/2, width, height/2, -90, -180);
        g.setStrokeStyle(Graphics.DOTTED);
        g.setColor(0xffff00);
        g.drawRect(0, height/2, width, height/2);        
    }
}
// A canvas that illustrates text rendering
class TextCanvas extends Canvas {
    public void paint(Graphics g) {
        int width = getWidth();
        int height = getHeight();
        // Create a black background
        g.setColor(0);
        g.fillRect(0, 0, width, height);
        
        // Top-left of canvas
        g.setColor(0xffffff);
        g.drawString("Top left", 0, 0, Graphics.TOP | Graphics.LEFT);
        
        // Draw another string one line below
        Font font = g.getFont();
        g.drawString("Below top left", 0, font.getHeight(), Graphics.TOP | Graphics.LEFT);
        
        // Bottom-right of canvas
        g.drawString("Bottom right", width, height, Graphics.BOTTOM | Graphics.RIGHT);
        
        // Mixed fonts and colors
        String str = "Multi-font ";        
        font = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_UNDERLINED, Font.SIZE_LARGE);
        g.setFont(font);
        g.drawString(str, 0, height/2, Graphics.LEFT | Graphics.BASELINE);
        
        int x = font.stringWidth(str);
        g.setColor(0x00ff00);
        g.setFont(Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD | Font.STYLE_ITALIC, Font.SIZE_MEDIUM));
        g.drawString("and multi-color", x, height/2, Graphics.LEFT | Graphics.BASELINE);
    }
}





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





Offscreen 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.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.midlet.MIDlet;
public class OffscreenMIDlet extends MIDlet {
  public void startApp() {
    Displayable d = new OffscreenCanvas();
    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 OffscreenCanvas extends Canvas {
  private Image mImage;
  public void paint(Graphics g) {
    if (mImage == null)
      initialize();
    g.drawImage(mImage, 0, 0, Graphics.TOP | Graphics.LEFT);
  }
  private void initialize() {
    int w = getWidth();
    int h = getHeight();
    mImage = Image.createImage(w, h);
    Graphics g = mImage.getGraphics();
    g.drawRect(0, 0, w - 1, h - 1);
    g.drawLine(0, 0, w - 1, h - 1);
    g.drawLine(w - 1, 0, 0, h - 1);
  }
}





Pacer

import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class Pacer extends MIDlet{ 
  public void startApp() { 
    Displayable d = new PacerCanvas();
    
    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 PacerCanvas extends Canvas { 
  public void paint(Graphics g) { 
    int w = getWidth();
    int h = getHeight();
    
    g.setColor(0xffffff);
    g.fillRect(0, 0, w, h);
    g.setColor(0x000000);
    for (int x = 0; x < w; x += 10)
      g.drawLine(0, w - x, x, 0);
    
    int z = 50;
    g.drawRect(z, z, 20, 20);
    z += 20;
    g.fillRoundRect(z, z, 20, 20, 5, 5);
    z += 20;
    g.drawArc(z, z, 20, 20, 0, 360);
  } 
}





Pointer Example

/*
J2ME: The Complete Reference
James Keogh
Publisher: McGraw-Hill
ISBN 0072227109
*/
//jad file (please verify the jar size)
/*
MIDlet-Name: PointerExample
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: PointerExample.jar
MIDlet-1: PointerExample, , PointerExample
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100
*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class PointerExample extends MIDlet
{
  private Display  display;       
  private MyClass canvas;   
  public PointerExample()
  {
    display = Display.getDisplay(this);
    canvas  = new MyClass (this);
  }
  protected void startApp()
  {
    display.setCurrent( canvas );
  }
  protected void pauseApp()
  { 
  }
  protected void destroyApp( boolean unconditional )
  { 
  }
  public void exitMIDlet()
  {
    destroyApp(true);
    notifyDestroyed();
  }
}
class MyClass extends Canvas implements CommandListener
{
  private Command exit;          
  private Command erase;  
  private boolean eraseFlag = false;
  private boolean isFirstPaint;
  private int sX = 0,sY = 0, cX = 0, cY = 0;
  private PointerExample pointerExample;
  public MyClass (PointerExample pointerExample)
  {
    this.pointerExample = pointerExample;
    exit = new Command("Exit", Command.EXIT, 1);
    erase = new Command("Erase", Command.SCREEN, 1);    
    addCommand(exit);
    addCommand(erase);
    setCommandListener(this);
    isFirstPaint = true;
  } 
  protected void paint(Graphics graphics)
  {
    if (eraseFlag || isFirstPaint)
    {
      graphics.setColor(255, 255, 255);
      graphics.fillRect(0, 0, getWidth(), getHeight());
      eraseFlag = isFirstPaint = false;
      sX = 0;
      sY = 0;
      cX = 0;
      cY = 0;
      return;
    }
    graphics.setColor(0, 0, 0);
    graphics.drawLine(sX, sY, cX, cY);
    sX = cX;
    sY = cY;
  }
  public void commandAction(Command command, Displayable displayable)
  {
    if (command == exit)
      pointerExample.exitMIDlet();
    else if (command == erase)
    {
      eraseFlag = true; 
      repaint();
    }
  }
  protected void pointerPressed(int x, int y)
  {
    sX = x;
    sY = y;
  }
  protected void pointerDragged(int x, int y)
  {
    cX = x;
    cY = y;       
    repaint();
  } 
}





Quatsch MIDlet

/*
Wireless Java 2nd edition 
Jonathan Knudsen
Publisher: Apress
ISBN: 1590590775 
*/
import java.io.IOException;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;
import javax.microedition.midlet.MIDlet;
public class QuatschMIDlet extends MIDlet
    implements CommandListener {
  private Display mDisplay;
  
  private QuatschCanvas mQuatschCanvas;
  private Form mShowForm;
  private Command mExitCommand, mShowCommand, mOkCommand;
  
  public void startApp() {
    if (mQuatschCanvas == null) {
      try {
        mQuatschCanvas = new QuatschCanvas("/quatsch.png",
            "/atmosphere.png", "/background_tiles.png");
        mQuatschCanvas.start();
        mExitCommand = new Command("Exit", Command.EXIT, 0);
        mShowCommand = new Command("Show/Hide", Command.SCREEN, 0);
        mOkCommand = new Command("OK", Command.OK, 0);
        mQuatschCanvas.addCommand(mExitCommand);
        mQuatschCanvas.addCommand(mShowCommand);
        mQuatschCanvas.setCommandListener(this);
      }
      catch (IOException ioe) {
        System.out.println(ioe);
      }
    }
    
    mDisplay = Display.getDisplay(this);
    mDisplay.setCurrent(mQuatschCanvas);
  }
  
  public void pauseApp() {}
  
  public void destroyApp(boolean unconditional) {
    mQuatschCanvas.stop();
  }
  
  public void commandAction(Command c, Displayable s) {
    if (c.getCommandType() == Command.EXIT) {
      destroyApp(true);
      notifyDestroyed();
    }
    else if (c == mShowCommand) {
      if (mShowForm == null) {
        mShowForm = new Form("Show/Hide");
        ChoiceGroup cg = new ChoiceGroup("Layers", Choice.MULTIPLE);
        cg.append("Fog", null);
        cg.append("Dr. Quatsch", null);
        cg.append("Background", null);
        mShowForm.append(cg);
        mShowForm.addCommand(mOkCommand);
        mShowForm.setCommandListener(this);
      }
      ChoiceGroup cg = (ChoiceGroup)mShowForm.get(0);
      cg.setSelectedIndex(0, mQuatschCanvas.isVisible(0));
      cg.setSelectedIndex(1, mQuatschCanvas.isVisible(1));
      cg.setSelectedIndex(2, mQuatschCanvas.isVisible(2));
      mDisplay.setCurrent(mShowForm);
    }
    else if (c == mOkCommand) {
      ChoiceGroup cg = (ChoiceGroup)mShowForm.get(0);
      mQuatschCanvas.setVisible(0, cg.isSelected(0));
      mQuatschCanvas.setVisible(1, cg.isSelected(1));
      mQuatschCanvas.setVisible(2, cg.isSelected(2));
      mDisplay.setCurrent(mQuatschCanvas);
    }
  }
}
class QuatschCanvas extends GameCanvas implements Runnable {
  private boolean mTrucking;
  
  private LayerManager mLayerManager;
  
  private TiledLayer mAtmosphere;
  private TiledLayer mBackground;
  private int mAnimatedIndex;
  
  private Sprite mQuatsch;
  private int mState, mDirection;
  
  private static final int kStanding = 1;
  private static final int kRunning = 2;
  
  private static final int kLeft = 1;
  private static final int kRight = 2;
  
  private static final int[] kRunningSequence = { 0, 1, 2 };
  private static final int[] kStandingSequence = { 3 };
  
  public QuatschCanvas(String quatschImageName,
      String atmosphereImageName, String backgroundImageName)
      throws IOException {
    super(true);
    
    // Create a LayerManager.
    mLayerManager = new LayerManager();
    int w = getWidth();
    int h = getHeight();
    mLayerManager.setViewWindow(96, 0, w, h);
    
    createBackground(backgroundImageName);
    createAtmosphere(atmosphereImageName);
    createQuatsch(quatschImageName);
  }
  
  private void createBackground(String backgroundImageName)
      throws IOException {
    // Create the tiled layer.
    Image backgroundImage = Image.createImage(backgroundImageName);
    int[] map = {
      1, 2, 0, 0, 0, 0, 0, 0,
      3, 3, 2, 0, 0, 0, 5, 0,
      3, 3, 3, 2, 4, 1, 3, 2,
      6, 6, 6, 6, 6, 6, 6, 6
    };
    mBackground = new TiledLayer(8, 4, backgroundImage, 48, 48);
    mBackground.setPosition(12, 0);
    for (int i = 0; i < map.length; i++) {
      int column = i % 8;
      int row = (i - column) / 8;
      mBackground.setCell(column, row, map[i]);
    }
    mAnimatedIndex = mBackground.createAnimatedTile(8);
    mBackground.setCell(3, 0, mAnimatedIndex);
    mBackground.setCell(5, 0, mAnimatedIndex);
    mLayerManager.append(mBackground);
  }
    
  private void createAtmosphere(String atmosphereImageName)
      throws IOException {
    // Create the atmosphere layer
    Image atmosphereImage = Image.createImage(atmosphereImageName);
    mAtmosphere = new TiledLayer(8, 1, atmosphereImage,
        atmosphereImage.getWidth(), atmosphereImage.getHeight());
    mAtmosphere.fillCells(0, 0, 8, 1, 1);
    mAtmosphere.setPosition(0, 96);
    mLayerManager.insert(mAtmosphere, 0);
  }
  private void createQuatsch(String quatschImageName)
      throws IOException {
    // Create the sprite.
    Image quatschImage = Image.createImage(quatschImageName);
    mQuatsch = new Sprite(quatschImage, 48, 48);
    mQuatsch.setPosition(96 + (getWidth() - 48) / 2, 96);
    mQuatsch.defineReferencePixel(24, 24);
    setDirection(kLeft);
    setState(kStanding);
    mLayerManager.insert(mQuatsch, 1);
  }
  public void start() {
    mTrucking = true;
    Thread t = new Thread(this);
    t.start();
  }
  
  public void run() {
    int w = getWidth();
    int h = getHeight();
    Graphics g = getGraphics();
    int frameCount = 0;
    int factor = 2;
    int animatedDelta = 0;
    
    while (mTrucking) {
      if (isShown()) {
        int keyStates = getKeyStates();
        if ((keyStates & LEFT_PRESSED) != 0) {
          setDirection(kLeft);
          setState(kRunning);
          mBackground.move(3, 0);
          mAtmosphere.move(3, 0);
          mQuatsch.nextFrame();
        }
        else if ((keyStates & RIGHT_PRESSED) != 0) {
          setDirection(kRight);
          setState(kRunning);
          mBackground.move(-3, 0);
          mAtmosphere.move(-3, 0);
          mQuatsch.nextFrame();
        }
        else {
          setState(kStanding);
        }
        
        frameCount++;
        if (frameCount % factor == 0) {
          int delta = 1;
          if (frameCount / factor < 10) delta = -1;
          mAtmosphere.move(delta, 0);
          if (frameCount / factor == 20) frameCount = 0;
          mBackground.setAnimatedTile(mAnimatedIndex,
              8 + animatedDelta++);
          if (animatedDelta == 3) animatedDelta = 0;
        }
        g.setColor(0x5b1793);
        g.fillRect(0, 0, w, h);
        
        mLayerManager.paint(g, 0, 0);
        
        flushGraphics();
      }
      
      try { Thread.sleep(80); }
      catch (InterruptedException ie) {}
    }
  }
  
  public void stop() {
    mTrucking = false;
  }
  
  public void setVisible(int layerIndex, boolean show) {
    Layer layer = mLayerManager.getLayerAt(layerIndex);
    layer.setVisible(show);
  }
  
  public boolean isVisible(int layerIndex) {
    Layer layer = mLayerManager.getLayerAt(layerIndex);
    return layer.isVisible();
  }
  
  private void setDirection(int newDirection) {
    if (newDirection == mDirection) return;
    if (mDirection == kLeft)
      mQuatsch.setTransform(Sprite.TRANS_MIRROR);
    else if (mDirection == kRight)
      mQuatsch.setTransform(Sprite.TRANS_NONE);
    mDirection = newDirection;
  }
  
  private void setState(int newState) {
    if (newState == mState) return;
    switch (newState) {
      case kStanding:
        mQuatsch.setFrameSequence(kStandingSequence);
        mQuatsch.setFrame(0);
        break;
      case kRunning:
        mQuatsch.setFrameSequence(kRunningSequence);
        break;
      default:
        break;
    }
    mState = newState;
  }
}





Show various anchor points

/*--------------------------------------------------
* Text.java
*
* Show various anchor points
*
* 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 Text extends MIDlet
{
  private Display  display;       // The display
  private TextCanvas canvas;      // Canvas to display text
  private AnchorPtList anchorPt;  // List to query for anchor point
  private int anchorPoint = Graphics.BASELINE | Graphics.HCENTER;
 
  public Text()
  {
    display = Display.getDisplay(this);
    canvas  = new TextCanvas(this);
    anchorPt = new AnchorPtList("Anchor point", List.IMPLICIT, this);    
  }
 
  protected void startApp()
  {
    showCanvas();  
  }
 
  protected void pauseApp()
  { }
  protected void destroyApp( boolean unconditional )
  { }
  public void showCanvas()
  {
    display.setCurrent(canvas);
  }
  public void showList()
  {
    display.setCurrent(anchorPt);
  }
   
  public int getAnchorPoint()
  {
    return anchorPoint;
  }
  
  public void setAnchorPoint(int anchorPoint)
  {
    this.anchorPoint = anchorPoint;
  }
 
  public void exitMIDlet()
  {
    destroyApp(true);
    notifyDestroyed();
  }
}
/*--------------------------------------------------
* Class TextCanvas
*
* Draw text at specified anchor point
*-------------------------------------------------*/
class TextCanvas extends Canvas implements CommandListener
{
  private Command cmExit;  // Exit midlet
  private Command cmGetAnchorPt;
  private Text midlet;
 
  public TextCanvas(Text midlet)
  {
    this.midlet = midlet;
    
    // Create commands & listen for events
    cmExit = new Command("Exit", Command.EXIT, 1);
    cmGetAnchorPt = new Command("Anchor", Command.SCREEN, 2);
    
    addCommand(cmExit);
    addCommand(cmGetAnchorPt);
    setCommandListener(this);
  } 
  /*--------------------------------------------------
  * Draw text 
  *-------------------------------------------------*/
  protected void paint(Graphics g)
  {
    int xcenter = getWidth() / 2,
        ycenter = getHeight() / 2;

    // Due to a bug in MIDP 1.0.3 we need to 
    // force a clear of the display
    g.setColor(255, 255, 255);                  // White pen
    g.fillRect(0, 0, getWidth(), getHeight());
    g.setColor(0, 0, 0);                        // Black pen
    // Choose a font
    g.setFont(Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_MEDIUM));
     
    // Draw a dot at the center of the display
    g.drawLine(xcenter, ycenter, xcenter, ycenter);
    
    // x and y are always at the center of the display 
    // Move the text around x and y based on the anchor point 
    g.drawString("go j2me!", xcenter, ycenter, midlet.getAnchorPoint());
  }
  /*--------------------------------------------------
  * Exit midlet or show anchor point selection list
  *-------------------------------------------------*/
  public void commandAction(Command c, Displayable d)
  {
    if (c == cmExit)
      midlet.exitMIDlet();
    else if (c == cmGetAnchorPt)
    {
      midlet.showList();      
    }
  }   
}
/*--------------------------------------------------
* Class AnchorPtList
*
* List to query for an anchor point
*-------------------------------------------------*/
class AnchorPtList extends List implements CommandListener
{
  private Text midlet;
  
  public AnchorPtList(String title, int listType, Text midlet)
  {
    // Call list constructor
    super(title, listType); 
    this.midlet = midlet;
    append("Top/Left", null);
    append("Top/HCenter", null);
    append("Top/Right", null);
    
    append("Baseline/Left", null);    
    append("Baseline/HCenter", null);
    append("Baseline/Right", null);
    
    append("Bottom/Left", null);    
    append("Bottom/HCenter", null);
    append("Bottom/Right", null);        
    
    setCommandListener(this);
  }
  /*--------------------------------------------------
  * Commands to set anchor point
  *-------------------------------------------------*/
  public void commandAction(Command c, Displayable s)
  {
    switch (getSelectedIndex())
    {
      case 0:
          midlet.setAnchorPoint(Graphics.TOP | Graphics.LEFT);
        break;
      case 1:
          midlet.setAnchorPoint(Graphics.TOP | Graphics.HCENTER);
        break;
        
      case 2:
        midlet.setAnchorPoint(Graphics.TOP | Graphics.RIGHT);
        break;        
      case 3:
        midlet.setAnchorPoint(Graphics.BASELINE | Graphics.LEFT);
        break;        
      case 4:
        midlet.setAnchorPoint(Graphics.BASELINE | Graphics.HCENTER);
        break;        
      case 5:
        midlet.setAnchorPoint(Graphics.BASELINE | Graphics.RIGHT);
        break;        
      case 6:
        midlet.setAnchorPoint(Graphics.BOTTOM | Graphics.LEFT);
        break;        
      case 7:
        midlet.setAnchorPoint(Graphics.BOTTOM | Graphics.HCENTER);
        break;        
      case 8:
        midlet.setAnchorPoint(Graphics.BOTTOM | Graphics.RIGHT);
        break;        
        
      default:
        midlet.setAnchorPoint(Graphics.BASELINE | Graphics.HCENTER);
    }
    midlet.showCanvas();
  }
}





Simple Canvas

/*
Title:  J2ME Games With MIDP2
Authors:  Carol Hamer
Publisher:  Apress
ISBN:   1590593820
*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
/**
 * This is the main class of the hello world demo.
 *
 * @author Carol Hamer
 */
public class Hello extends MIDlet implements CommandListener {
  /**
   * The canvas is the region of the screen that has been allotted 
   * to the game.
   */
  HelloCanvas myCanvas;
  /**
   * The Command objects appear as buttons in this example.
   */
  private Command exitCommand = new Command("Exit", Command.EXIT, 99);
  /**
   * The Command objects appear as buttons in this example.
   */
  private Command toggleCommand = new Command("Toggle Msg", Command.SCREEN, 1);
  /**
   * Initialize the canvas and the commands.
   */
  public Hello() {
    myCanvas = new HelloCanvas();
    myCanvas.addCommand(exitCommand);
    myCanvas.addCommand(toggleCommand);
    // we set one command listener to listen to all 
    // of the commands on the canvas:
    myCanvas.setCommandListener(this);
  }
  //----------------------------------------------------------------
  //  implementation of MIDlet
  /**
   * Start the application.
   */
  public void startApp() throws MIDletStateChangeException {
    // display my canvas on the screen:
    Display.getDisplay(this).setCurrent(myCanvas);
    myCanvas.repaint();
  }
  
  /**
   * If the MIDlet was using resources, it should release 
   * them in this method.
   */
  public void destroyApp(boolean unconditional) 
      throws MIDletStateChangeException {
  }
  /**
   * This method is called to notify the MIDlet to enter a paused 
   * state.  The MIDlet should use this opportunity to release 
   * shared resources.
   */
  public void pauseApp() {
  }
  //----------------------------------------------------------------
  //  implementation of CommandListener
  /*
   * Respond to a command issued on the Canvas.
   * (either reset or exit).
   */
  public void commandAction(Command c, Displayable s) {
    if(c == toggleCommand) {
      myCanvas.toggleHello();
    } else if(c == exitCommand) {
      try {
  destroyApp(false);
  notifyDestroyed();
      } catch (MIDletStateChangeException ex) {
      }
    }
  }
  
}

/**
 * This class represents the region of the screen that has been allotted 
 * to the game.
 * 
 * @author Carol Hamer
 */
class HelloCanvas extends Canvas {
  //---------------------------------------------------------
  //   fields
  /**
   * whether or not the screen should currently display the 
   * "hello world" message.
   */
  boolean mySayHello = true;
  //-----------------------------------------------------
  //    initialization and game state changes
  /**
   * toggle the hello message.
   */
  void toggleHello() {
    mySayHello = !mySayHello;
    repaint();
  }
  //-------------------------------------------------------
  //  graphics methods
  /**
   * clear the screen and display the hello world message if appropriate.
   */
  public void paint(Graphics g) {
    // get the dimensions of the screen:
    int width = getWidth();
    int height = getHeight();
    // clear the screen (paint it white):
    g.setColor(0xffffff);
    // The first two args give the coordinates of the top 
    // left corner of the rectangle.  (0,0) corresponds 
    // to the top left corner of the screen.
    g.fillRect(0, 0, width, height);
    // display the hello world message if appropriate:.
    if(mySayHello) {
      Font font = g.getFont();
      int fontHeight = font.getHeight();
      int fontWidth = font.stringWidth("Hello World!");
      // set the text color to red:
      g.setColor(255, 0, 0);
      g.setFont(font);
      // write the string in the center of the screen
      g.drawString("Hello World!", (width - fontWidth)/2, 
       (height - fontHeight)/2,
       g.TOP|g.LEFT);
    }
  }
}





Text Example

//jad file (please verify the jar size)
/*
MIDlet-Name: TextExample
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: TextExample.jar
MIDlet-1: TextExample, , TextExample
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100
*/
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 TextExampleMIDlet extends MIDlet {
  private Display display;
  private MyCanvas canvas;
  public TextExampleMIDlet() {
    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 TextExampleMIDlet textExample;
  public MyCanvas(TextExampleMIDlet textExample) {
    this.textExample = textExample;
    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.setFont(Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_SMALL));
    graphics.drawString("Profound statement.", 50, 10, Graphics.HCENTER | Graphics.BASELINE);
  }
  public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
      textExample.exitMIDlet();
    }
  }
}





Text 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.Graphics;
import javax.microedition.midlet.MIDlet;
public class TextMIDlet extends MIDlet {
  public void startApp() {
    Displayable d = new TextCanvas();
    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 TextCanvas extends Canvas {
  public void paint(Graphics g) {
    int w = getWidth();
    int h = getHeight();
    g.setColor(0xffffff);
    g.fillRect(0, 0, w, h);
    g.setColor(0x000000);
    g.drawString("corner", 0, 0, Graphics.TOP | Graphics.LEFT);
    g.drawString("corner", w, 0, Graphics.TOP | Graphics.RIGHT);
    g.drawString("corner", 0, h, Graphics.BOTTOM | Graphics.LEFT);
    g.drawString("corner", w, h, Graphics.BOTTOM | Graphics.RIGHT);
    g.drawString("Sin Wagon", w / 2, h / 2, Graphics.BASELINE | Graphics.HCENTER);
  }
}





Translate Coordinates

/*
J2ME: The Complete Reference
James Keogh
Publisher: McGraw-Hill
ISBN 0072227109
*/
//jad file (please verify the jar size)
/*
MIDlet-Name: TranslateCoordinates
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: TranslateCoordinates.jar
MIDlet-1: TranslateCoordinates, , TranslateCoordinates
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100
*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class TranslateCoordinates extends MIDlet
{
  private Display  display;     
  private MyCanvas canvas;   
  public TranslateCoordinates ()
  {
    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 TranslateCoordinates translateCoordinates;
    private Image image = null;
    public MyCanvas(TranslateCoordinates translateCoordinates)
    {
      this. translateCoordinates = translateCoordinates;
      exit = new Command("Exit", Command.EXIT, 1);
      addCommand(exit);
      setCommandListener(this);
      try
      {
        image = Image.createImage(70, 70);
        Graphics graphics = image.getGraphics();
        graphics.setColor(255,0,0);
        graphics.fillArc(10, 10, 60, 50, 180, 180);      
      }
      catch (Exception error)
      {
        Alert alert = new Alert("Failure", 
                         "Creating Image", null, null);
        alert.setTimeout(Alert.FOREVER);
        display.setCurrent(alert);
      }    
    } 
    protected void paint(Graphics graphics)
    {
      if (image != null)
      {
       graphics.setColor(255,255,255);
       graphics.fillRect(0, 0, getWidth(), getHeight());
       graphics.translate(45, 45);
       graphics.drawImage(image, 0, 0, 
                      Graphics.VCENTER | Graphics.HCENTER);    }
    }
    public void commandAction(Command command, Displayable display)
    {
      if (command == exit)
      {
        translateCoordinates.exitMIDlet();
      }
    }
  }
}





Translate coordinate system

/*--------------------------------------------------
* Translate.java
*
* Translate coordinate system
*
* 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 Translate extends MIDlet
{
  private Display  display;     // The display
  private TranslateCanvas canvas;   // Canvas 
 
  public Translate()
  {
    display = Display.getDisplay(this);
    canvas  = new TranslateCanvas(this);
  }
 
  protected void startApp()
  {
    display.setCurrent( canvas );
  }
 
  protected void pauseApp()
  { }
  protected void destroyApp( boolean unconditional )
  { }
 
  public void exitMIDlet()
  {
    destroyApp(true);
    notifyDestroyed();
  }
}
/*--------------------------------------------------
* Class Translate
*
* Draw image using translated coordinates
*-------------------------------------------------*/
class TranslateCanvas extends Canvas implements CommandListener
{
  private Command cmExit;  // Exit midlet
  private Translate midlet;
  private Image im = null;
  private int translatex = 0, translatey = 0;
 
  public TranslateCanvas(Translate midlet)
  {
    this.midlet = midlet;
    
    // Create exit command & listen for events
    cmExit = new Command("Exit", Command.EXIT, 1);
    addCommand(cmExit);
    setCommandListener(this);
    try
    {
      // Create immutable image
      im = Image.createImage("/bolt.png");
    }
    catch (java.io.IOException e)
    {
      System.err.println("Unable to locate or read .png file");
    }    
  } 
  protected void paint(Graphics g)
  {
    if (im != null)
    {
      // Clear the background
      g.setColor(255, 255, 255);
      g.fillRect(0, 0, getWidth(), getHeight());
      
      // Translate coordinates
      g.translate(translatex, translatey);      
    
      // Always draw at 0,0
      g.drawImage(im, 0, 0, Graphics.LEFT | Graphics.TOP);
    }
  }
  public void commandAction(Command c, Displayable d)
  {
    if (c == cmExit)
      midlet.exitMIDlet();
  }
  
  protected void keyPressed(int keyCode)
  {
    switch (getGameAction(keyCode))
    {
      case UP: 
      
        // If scrolling off the top, roll around to bottom
        if (translatey - im.getHeight() < 0)
          translatey = getHeight() - im.getHeight();
        else
          translatey -= im.getHeight();          
        break;
      
      case DOWN:
        // If scrolling off the bottom, roll around to top
        if ((translatey + im.getHeight() + im.getHeight()) > getHeight())
          translatey = 0;
        else
          translatey += im.getHeight();          
        break;
        
      case LEFT:
      
        // If scrolling off the left, bring around to right
        if (translatex - im.getWidth() < 0)
          translatex = getWidth() - im.getWidth();
        else
          translatex -= im.getWidth();          
        break;
      case RIGHT:
      
        // If scrolling off the right, bring around to left
        if ((translatex + im.getWidth() + translatex) > getWidth())
          translatex = 0;
        else
          translatex += im.getWidth();          
        break;
    }        
    repaint();
  }
}





Use pointer events to draw onto the Canvas

/*--------------------------------------------------
* Doodle.java
*
* Use pointer events to draw onto the Canvas
*
* 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 Doodle extends MIDlet
{
  private Display  display;       // The display
  private DoodleCanvas canvas;   // Canvas 
 
  public Doodle()
  {
    display = Display.getDisplay(this);
    canvas  = new DoodleCanvas(this);
  }
 
  protected void startApp()
  {
    display.setCurrent( canvas );
  }
 
  protected void pauseApp()
  { }
  protected void destroyApp( boolean unconditional )
  { }
 
  public void exitMIDlet()
  {
    destroyApp(true);
    notifyDestroyed();
  }
}
/*--------------------------------------------------
* Class DoodleCanvas
*
* Pointer event handling
*-------------------------------------------------*/
class DoodleCanvas extends Canvas implements CommandListener
{
  private Command cmExit;          // Exit midlet
  
  private Command cmClear;         // Clear display
  
  private int startx = 0,   // Where pointer was clicked
              
              starty = 0,
              
              currentx = 0, // Current location
              
              currenty = 0;
  private Doodle midlet;
  private boolean clearDisplay = false;
  /*--------------------------------------------------
  * Constructor
  *-------------------------------------------------*/
  public DoodleCanvas(Doodle midlet)
  {
    this.midlet = midlet;
    
    // Create exit command & listen for events
    cmExit = new Command("Exit", Command.EXIT, 1);
    cmClear = new Command("Clear", Command.SCREEN, 1);    
    addCommand(cmExit);
    addCommand(cmClear);
    setCommandListener(this);
  } 
  /*--------------------------------------------------
  * Paint the text representing the key code 
  *-------------------------------------------------*/
  protected void paint(Graphics g)
  {
    // Clear the background (to white)
    if (clearDisplay)
    {
      g.setColor(255, 255, 255);
      g.fillRect(0, 0, getWidth(), getHeight());
      
      clearDisplay = false;
      startx = currentx = starty = currenty = 0;
      
      return;
    }
    
    // Draw with black pen
    g.setColor(0, 0, 0);
    
    // Draw line
    g.drawLine(startx, starty, currentx, currenty);
    
    // New starting point is the current position
    startx = currentx;
    starty = currenty;
  }
  /*--------------------------------------------------
  * Command event handling
  *-------------------------------------------------*/  
  public void commandAction(Command c, Displayable d)
  {
    if (c == cmExit)
      midlet.exitMIDlet();
    else if (c == cmClear)
    {
      clearDisplay = true; 
      repaint();
    }
  }
  /*--------------------------------------------------
  * Pointer pressed
  *-------------------------------------------------*/  
  protected void pointerPressed(int x, int y)
  {
    startx = x;
    starty = y;
  }
  /*--------------------------------------------------
  * Pointer moved
  *-------------------------------------------------*/  
  protected void pointerDragged(int x, int y)
  {
    currentx = x;
    currenty = y;       
    repaint();
  } 
}