Java Tutorial/J2ME/Screen Buffer

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

Off screen canvas

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;
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(w - 1, 0, 0, h - 1);
  }
}
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) {
  }
}





Use Image as buffer

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.midlet.MIDlet;
public class ImageBufferGraphicsMIDlet extends MIDlet {
  private Display display;
  protected void startApp() {
    Canvas canvas = new LineCanvas();
    display = Display.getDisplay(this);
    display.setCurrent(canvas);
  }
  protected void pauseApp() {
  }
  protected void destroyApp(boolean unconditional) {
  }
}
class LineCanvas extends Canvas {
  public void paint(Graphics g) {
        int width = getWidth();
        int height = getHeight();
        Image image = Image.createImage(width, height);
        Graphics imageGraphics = image.getGraphics();
        imageGraphics.fillRect(0, 0, width, height);
        int count = 10;
        int yIncrement = height/count;
        int xIncrement = width/count;
        for (int i = 0, x = xIncrement, y = 0; i < count; i++) {
            imageGraphics.setColor(0xC0 + ((128 + 10 * i) << 8) + ((128 + 10 * i) << 16));
            imageGraphics.drawLine(0, y, x, height);
            y += yIncrement;
            x += xIncrement;
        }
        imageGraphics.setFont(Font.getFont(Font.FACE_PROPORTIONAL,
                                Font.STYLE_UNDERLINED, Font.SIZE_SMALL));
        imageGraphics.setColor(0xffff00);
        imageGraphics.drawString("Image Graphics", width/2, 0, Graphics.TOP | Graphics.HCENTER);
        g.drawImage(image, 0, 0, Graphics.TOP | Graphics.LEFT);
  }
}