/* This application inteds to create a small gaming with guessing what is on display - use of random numbers for starting the coordinates */ import javax.microedition.lcdui.*; import javax.microedition.midlet.*; import java.util.*; public class Clipping extends MIDlet{ private Display display; private ClippingCanvas canvas; // constructor public Clipping(){ display = Display.getDisplay(this); canvas = new ClippingCanvas(this); } // startApp protected void startApp(){ display.setCurrent(canvas); } // pauseApp protected void pauseApp(){ } // destroyApp protected void destroyApp(boolean unconditional){ } // exitMIDlet public void exitMIDlet(){ destroyApp(true); notifyDestroyed(); } // create ClippingCanvas class class ClippingCanvas extends Canvas implements CommandListener{ private Command cmExit; private Clipping midlet; private Image photo = null; // image for display private Random ran; // random number private int clx = 50; // clip start coordinates private int cly = 50; // clip start coordinates private int clw = 100; // clipping area private int clh = 100; // clipping srea private int oldclx = 50; // previous clipping area private int oldcly = 50; // previous clipping are public ClippingCanvas(Clipping midlet){ this.midlet = midlet; // create command and listen for events cmExit = new Command("Exit", Command.EXIT, 1); addCommand(cmExit); setCommandListener(this); // Provide a random number as a starting point ran = new java.util.Random(); // make the entire clipping are on the display clx = Math.min((getWidth()-clw), (ran.nextInt() >>> 1) % getWidth()); cly = Math.min((getHeight() - clh), (ran.nextInt() >>> 1) % getHeight()); // try and catch - immutable image try { photo = Image.createImage("/photo.png"); } catch(java.io.IOException e){ System.err.print("Unable to read or access file"); } } protected void paint(Graphics g){ if(photo != null) { // clear the previous clipping area g.setColor(255, 255, 255); g.fillRect(oldclx, oldcly, clw, clh); // set the new clipping area g.setClip(clx, cly, clw, clh); // draw the image g.drawImage(photo, 0, 0, Graphics.LEFT | Graphics.TOP); } } public void commandAction(Command c, Displayable d){ if(c == cmExit) midlet.exitMIDlet(); } protected void keyPressed(int keyCode){ // store the last clipping area oldclx = clx; oldcly = cly; switch(getGameAction(keyCode)){ case UP: // transfer clipping area up 4 pixel if(cly >0) cly = Math.max(0, cly - 4); break; case DOWN: // move the clipping area 4 pxels down if(cly + clh < getHeight()) cly = Math.min(getHeight(), cly + 4); break; case LEFT: // move clipping area 4 pixels left if(clx > 0) clx = Math.max(0, clx - 4); break; case RIGHT: // move clipping 4 pixels if(clx + clw < getWidth()) clx = Math.min(getWidth(), clx + 4); break; // Use fire to show the complete image case FIRE: clx = cly = 0; clw = getWidth(); clh = getHeight(); } repaint(); } } }