Mega Code Archive

 
Categories / Java Tutorial / J2ME
 

Navigatable Canvas

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