// A freehand application on canvas using pointer events to draw onto canvas import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class Freehand extends MIDlet { private Display display; // A display private DoodleCanvas canvas; // A canvas providing doodling with pen and paper public Freehand() { display = Display.getDisplay(this); canvas = new DoodleCanvas(this); } protected void startApp(){ display.setCurrent(canvas); } protected void pauseApp(){ } protected void destroyApp(boolean unconditional){ } public void exitMidlet(){ destroyApp(true); notifyDestroyed(); } } // pointer event handle - Class DoodleCanvas class DoodleCanvas extends Canvas implements CommandListener{ private Command cmExit; // Exit private Command cmClear; // clear canvas command private int startx = 0, starty = 0, currentx = 0, currenty = 0; private Freehand midlet; private boolean clearDisplay = false; // set the clearDisplay to false // constructor public DoodleCanvas(Freehand midlet) { this.midlet = midlet; // create exit command & listen for events cmExit = new Command("Exit", Command.EXIT, 1); cmClear = new Command("Clear", Command.SCREEN, 1); addCommand(cmExit); addCommand(cmClear); setCommandListener(this); } // Print the text illustrating the key code protected void paint(Graphics g){ // Clear background if(clearDisplay){ g.setColor(255,255,255); g.fillRect(0, 0, getWidth(),getHeight()); clearDisplay = false; startx = currentx = starty = currenty = 0; // start from 0,0 return; } // draw with blue pen g.setColor(0, 0, 255); //draw line g.drawLine(startx, starty, currentx, currenty); // New starting point is current position startx = currentx; starty = currenty; } // event handling public void commandAction(Command c, Displayable d) { if (c == cmExit) midlet.exitMidlet(); else if (c == cmClear){ clearDisplay = true; repaint(); } } // pointer pressed protected void pointerPressed(int x, int y) { startx = x; starty = y; } // pointer moved protected void pointerDragged(int x, int y) { currentx = x; currenty = y; repaint(); } }