Java Tutorial/J2ME/Canvas

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

Canvas key event and navigate through arrow keys

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





Canvas key pressed and key typed events

/* License
 * 
 * Copyright 1994-2004 Sun Microsystems, Inc. All Rights Reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *  
 *  * Redistribution of source code must retain the above copyright notice,
 *      this list of conditions and the following disclaimer.
 * 
 *  * Redistribution in binary form must reproduce the above copyright notice,
 *      this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 * 
 * Neither the name of Sun Microsystems, Inc. or the names of contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *  
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *  
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility. 
 */
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 EventEx3 extends MIDlet {
  Display display;
  Command exit;
  public EventEx3() {
    display = Display.getDisplay(this);
  }
  public void destroyApp(boolean unconditional) {
  }
  public void pauseApp() {
    System.out.println("App paused.");
  }
  public void startApp() {
    display = Display.getDisplay(this);
    Canvas canvas = new Canvas() { // anonymous class
      public void paint(Graphics g) {
      }
      protected void keyPressed(int keyCode) {
        if (keyCode > 0) {
          System.out.println("keyPressed " + ((char) keyCode));
        } else {
          System.out.println("keyPressed action " + getGameAction(keyCode));
        }
      }
      protected void keyReleased(int keyCode) {
        if (keyCode > 0) {
          System.out.println("keyReleased " + ((char) keyCode));
        } else {
          System.out.println("keyReleased action " + getGameAction(keyCode));
        }
      }
    }; // end of anonymous class
    exit = new Command("Exit", Command.STOP, 1);
    canvas.addCommand(exit);
    canvas.setCommandListener(new CommandListener() {
      public void commandAction(Command c, Displayable d) {
        if (c == exit) {
          notifyDestroyed();
        } else {
          System.out.println("Saw the command: " + c);
        }
      }
    });
    display.setCurrent(canvas);
  }
}





Canvas size

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 CanvasSizeMIDlet extends MIDlet implements CommandListener {
  private Command exitCommand;
  Display display;
  public void startApp() {
    display = Display.getDisplay(this);
    exitCommand = new Command("Exit", Command.EXIT, 1);
    Displayable SizeCanvas = new SizeCanvas();
    SizeCanvas.addCommand(exitCommand);
    SizeCanvas.setCommandListener(this);
    display.setCurrent(SizeCanvas);
  }
  public void pauseApp() {
  }
  public void destroyApp(boolean unconditional) {
  }
  public void commandAction(Command c, Displayable s) {
    if (c == exitCommand) {
      destroyApp(false);
      notifyDestroyed();
    }
  }
}
class SizeCanvas extends Canvas {
  int width = 0;
  int height = 0;
  public void paint(Graphics g) {
    width = getWidth();
    height = getHeight();
    g.setGrayScale(255);
    g.fillRect(0, 0, width - 1, height - 1);
    g.setGrayScale(0);
    g.drawString("Stroke Style:" + g.getStrokeStyle(), 0, 60, Graphics.TOP | Graphics.LEFT);
    g.drawRect(0, 0, width - 1, height - 1);
    g.setStrokeStyle(Graphics.DOTTED);
    g.drawLine(00, 40, 60, 60);
    g.drawString(Integer.toBinaryString(width), 0, 0, Graphics.TOP | Graphics.LEFT);
    g.drawString(Integer.toBinaryString(height), 10, 20, Graphics.TOP | Graphics.LEFT);
  }
}





extends Canvas to create your own drawable area

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Graphics;
import javax.microedition.midlet.MIDlet;
public class CanvasMyMidlet extends MIDlet {
  public CanvasMyMidlet() { // constructor
  }
  public void startApp() {
    Canvas canvas = new MyCanvas();
    Display display = Display.getDisplay(this);
    display.setCurrent(canvas);
  }
  public void pauseApp() {
  }
  public void destroyApp(boolean unconditional) {
  }
}
class MyCanvas extends Canvas {
  public void paint(Graphics g) {
    g.setColor(255, 0, 0);
    g.fillRect(0, 0, getWidth(), getHeight());
    g.setColor(255, 255, 255);
    g.drawString("Hello World!", 0, 0, g.TOP | g.LEFT);
  }
}





Get Canvas properties

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.Form;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.MIDlet;
public class AttributesMIDlet extends MIDlet 
                        implements CommandListener {
    private Display display;
        
    protected boolean started;
    private Command exitCommand;
    
    protected void startApp() {
        if (!started) {
            display = Display.getDisplay(this);
            Canvas canvas = new DummyCanvas();
            Form form = new Form("Attributes");
            exitCommand = new Command("Exit", Command.EXIT, 0);
            form.addCommand(exitCommand);
            
            boolean isColor = display.isColor();
            form.append(new StringItem(isColor ? "Colors: " : "Grays: ",
                                String.valueOf(display.numColors())));
            form.append(new StringItem("Width: ", String.valueOf(canvas.getWidth())));
            form.append(new StringItem("Height: ", String.valueOf(canvas.getHeight())));
            form.append(new StringItem("Pointer? ", String.valueOf(canvas.hasPointerEvents())));
            form.append(new StringItem("Motion? ",String.valueOf(canvas.hasPointerMotionEvents())));
            form.append(new StringItem("Repeat? ",String.valueOf(canvas.hasRepeatEvents())));
            form.append(new StringItem("Buffered? ", String.valueOf(canvas.isDoubleBuffered())));
            
            form.setCommandListener(this);
            display.setCurrent(form);
            
            started = true;
        }
    }
    protected void pauseApp() {
    }
    protected void destroyApp(boolean unconditional) {
    }
    public void commandAction(Command c, Displayable d) {
        if (c == exitCommand) {
            notifyDestroyed();
        }
    } 
    static class DummyCanvas extends Canvas {
        protected void paint(Graphics g) {
        }
    }
}





Navigatable 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;
public class NavigateMIDlet extends MIDlet implements CommandListener {
  int stepX;
  int stepY;
  private Command leftCommand;
  private Command rightCommand;
  private Display display;
  Displayable nd;
  Image image = null;
  public NavigateMIDlet() {
    try {
      image = Image.createImage("/M.png");
    } catch (Exception e) {
    }
    Display display = Display.getDisplay(this);
    nd = new NavigateCanvas(image);
    stepX = ((NavigateCanvas) nd).getWidth() / 4;
    stepY = ((NavigateCanvas) nd).getHeight() / 4;
    leftCommand = new Command("<Left", Command.SCREEN, 1);
    rightCommand = new Command("Right>", Command.SCREEN, 1);
    nd.addCommand(rightCommand);
    nd.addCommand(leftCommand);
    nd.setCommandListener(this);
    display.setCurrent(nd);
  }
  public void startApp() {
  }
  public void pauseApp() {
  }
  public void destroyApp(boolean unconditional) {
  }
  public void commandAction(Command c, Displayable d) {
    if (d == nd && c == leftCommand) {
      ((NavigateCanvas) nd).steppingXY(stepX, 0);
      ((NavigateCanvas) nd).repaint();
    } else if (d == nd && c == rightCommand) {
      ((NavigateCanvas) nd).steppingXY(-stepX, 0);
      ((NavigateCanvas) nd).repaint();
    }
  }
}
class NavigateCanvas extends Canvas {
  private Image image;
  private int newX = 0;
  private int newY = 0;
  public NavigateCanvas(Image image) {
    this.image = image;
    newX = 0;
    newY = 0;
  }
  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);
  }
}





Use Canvas to draw a clock

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 ClockMIDlet extends MIDlet implements CommandListener {
  private Command exitCommand;
  Display display;
  public void startApp() {
    Display display = Display.getDisplay(this);
    Displayable d = new ClockCanvas(10, 10, 10);
    exitCommand = new Command("Exit", Command.EXIT, 1);
    d.addCommand(exitCommand);
    d.setCommandListener(this);
    display.setCurrent(d);
  }
  public void pauseApp() {
  }
  public void destroyApp(boolean unconditional) {
  }
  public void commandAction(Command c, Displayable s) {
    notifyDestroyed();
  }
}
class ClockCanvas extends Canvas {
  private int hour;
  private int minute;
  private int second;
  protected int xCenter, yCenter;
  protected int clockRadius;
  int width = 0;
  int height = 0;
  ClockCanvas(int hour, int minute, int second) {
    this.hour = hour;
    this.minute = minute;
    this.second = second;
  }
  public void paint(Graphics g) {
    width = getWidth();
    height = getHeight();
    g.setGrayScale(255);
    g.fillRect(0, 0, width - 1, height - 1);
    g.setGrayScale(0);
    g.drawRect(0, 0, width - 1, height - 1);
    clockRadius = Math.min(width, height) - 20;
    xCenter = getWidth() / 2;
    yCenter = getHeight() / 2;
    g.drawArc(10, 12, clockRadius, clockRadius, 0, 360);
    g.drawString("12", xCenter, 0, Graphics.TOP | Graphics.HCENTER);
    g.drawString("9", 1, yCenter, Graphics.BASELINE | Graphics.LEFT);
    g.drawString("3", width - 1, yCenter, Graphics.BASELINE | Graphics.RIGHT);
    g.drawString("6", xCenter, height, Graphics.BOTTOM | Graphics.RIGHT);
  }
}