// This exercise midlet creates an application to translate coordinate import javax.microedition.lcdui.*; import javax.microedition.midlet.*; public class Trans extends MIDlet { private Display display; private TransCanvas canvas; // constructor public Trans(){ display = Display.getDisplay(this); canvas = new TransCanvas(this); } // startApp protected void startApp(){ display.setCurrent(canvas); } // pauseApp protected void pauseApp(){ } // detsroyApp protected void destroyApp(boolean unconditional){ } // exitMIDlet public void exitMIDlet(){ destroyApp(true); notifyDestroyed(); } } // Class TRanCanvas --- Draw image using translate coordinates class TransCanvas extends Canvas implements CommandListener{ private Command cmExit; private Trans midlet; private Image sub = null; private int tranx = 0; private int trany = 0; // constructor public TransCanvas(Trans midlet){ this.midlet = midlet; // Create command and listen for events cmExit = new Command("Exit", Command.EXIT, 1); addCommand(cmExit); setCommandListener(this); // try and catch exception try { // Create image sub = Image.createImage("/sub.png"); } catch(java.io.IOException e) { System.err.println("Unable to find or read *.png file"); } } // Paint the image on canvas protected void paint(Graphics g){ if(sub !=null){ // Clear the background by setting color to Light blue and fill the display g.setColor(0, 255, 255); g.fillRect(0, 0, getWidth(), getHeight()); //Translate cooridinates g.translate(tranx, trany); // Draw from 5, 5 coordinates g.drawImage(sub, 5, 5, Graphics.LEFT | Graphics.TOP); } } // command action public void commandAction(Command c, Displayable s){ if(c == cmExit) midlet.exitMIDlet(); } // keyPressed game actions protected void keyPressed(int keyCode){ switch(getGameAction(keyCode)){ case UP: // if scrolling on tthe top, roll around to bottom if(trany - sub.getHeight() < 0) trany = getHeight() - sub.getHeight(); // else go one image height up else trany -= sub.getHeight(); break; case DOWN: // if scrolling off the bottom roll arounf the top if((trany + sub.getHeight() + sub.getHeight()) > getHeight()) trany = 0; // esle go one image height down else trany += sub.getHeight(); break; case LEFT: // if scrolling off the left bring around to right if(tranx - sub.getWidth() < 0) tranx = getWidth() - sub.getWidth(); else tranx -= sub.getWidth(); break; case RIGHT: // if scrolling goes off the right bring round to the left if((tranx + sub.getWidth() + tranx) > getWidth()) tranx = 0; else tranx += sub.getWidth(); break; } repaint(); } }