mobile computing pracs

Upload: prizmwave

Post on 06-Apr-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 Mobile Computing Pracs

    1/30

    M.Sc CS Part I J2ME

    1

    API Specifications

    The common methods, packages, listeners, classes etc. used in the majorprograms are as follows:

    1. Packages : The main packages used are midlet and lcdui

    a. javax.microedition.midlet : The MIDlet package defines MobileInformation Device Profile applications and the interactions between theapplication and the environment in which the application runs.

    b. javax.microedition.lcdui : The UI API provides a set of features forimplementation of user interfaces for MIDP applications.

    c. java.io: Provides classes for input and output through data streams.d. java.lang: Provides classes that are fundamental to the Java programming

    language.e. java.util: Contains the collection classes, and the date and time facilities.

    2. Classes: The most important class which has to be extended by the usercreated class is MIDlet class. With this the user can extend many other classesnamely Canvas, Timer, TimerTask, etc. The other classes which are mainly usedare Display, Command, Form, ChoiceGroup, Font, Image, Graphics etc.

    3. Listeners:

    a. CommandListener : This interface is used by applications which need toreceive high-level events from the implementation

    b. ItemStateListener : This interface is used by applications which need toreceive events that indicate changes in the internal state of the interactiveitems within a Form screen.

    c. Runnable :The Runnable interface should be implemented by any classwhose instances are intended to be executed by a thread. The class mustdefine a method of no arguments called run.

    4. Methods of various Classes and Interfaces:

    a. MIDlet

    protected abstractvoid

    destroyApp(boolean unconditional)

    Signals the MIDlet to terminate and enter theDestroyedstate.

    void notifyDestroyed()Used by an MIDlet to notify the application

    management software that it has entered into theDestroyedstate.

    protected abstractvoid pauseApp()

  • 8/3/2019 Mobile Computing Pracs

    2/30

    M.Sc CS Part I J2ME

    2

    Signals the MIDlet to enter the Pausedstate.

    protected abstractvoid

    startApp()Signals the MIDlet that it has entered the Active

    state.

    b. Display

    void callSerially(Runnable r):Causes the Runnable object rtohave its run() method called later, serialized with theevent stream, soon after completion of the repaint cycle.

    static Display getDisplay(MIDlet m)Gets the Display object that is unique to this MIDlet.

    void setCurrent(Displayable nextDisplayable)Requests that a different Displayable object be

    made visible on the display.

    c. Canvas

    int getGameAction(int keyCode)Gets the game action associated with the given

    key code of the device.

    boolean isDoubleBuffered()Checks if the Canvas is double buffered by the

    implementation.

    protected abstractvoid paint(Graphics g)Renders the Canvas.

    void repaint()Requests a repaint for the entire Canvas.

    d. Graphics

    Void drawArc(int x, int y, int width, int height, int startAngle,int arcAngle)

    Draws the outline of a circular or elliptical arccovering the specified rectangle, using the current

    color and stroke style.

    Void drawImage(Image img, int x, int y, int anchor)Draws the specified image by using the

    anchor point.

    void drawLine(int x1, int y1, int x2, int y2)Draws a line between the coordinates (x1,y1)

    and (x2,y2) using the current color and stroke style.

  • 8/3/2019 Mobile Computing Pracs

    3/30

    M.Sc CS Part I J2ME

    3

    Void drawRect(int x, int y, int width, int height)Draws the outline of the specified rectangle

    using the current color and stroke style.

    Void drawRoundRect(int x, int y, int width, int height,int arcWidth, int arcHeight)

    Draws the outline of the specified roundedcorner rectangle using the current color and strokestyle.

    Void drawString(String str, int x, int y, int anchor)Draws the specified String using the current

    font and color.

    Void fillArc(int x, int y, int width, int height, int startAngle,int arcAngle)

    Fills a circular or elliptical arc covering thespecified rectangle.

    Void fillRect(int x, int y, int width, int height)Fills the specified rectangle with the current

    color.

    Void fillRoundRect(int x, int y, int width, int height, int arcWidth,int arcHeight)

    Fills the specified rounded corner rectanglewith the current color.

    Font getFont()Gets the current font.

    Void setColor(int RGB)

    Sets the current color to the specified RGBvalues.

    Void setColor(int red, int green, int blue)Sets the current color to the specified RGB

    values.

    Void setFont(Font font)Sets the font for all subsequent text rendering

    operations.

    Void setGrayScale(int value)Sets the current grayscale to be used for all

    subsequent rendering operations.

    e. Font

    static Font getDefaultFont()Gets the default font of the system.

  • 8/3/2019 Mobile Computing Pracs

    4/30

    M.Sc CS Part I J2ME

    4

    static Font getFont(int fontSpecifier)Gets the Font used by the high level user

    interface for the fontSpecifierpassed in.

    static Font getFont(int face, int style, int size)Obtains an object representing a font having

    the specified face, style, and size.

    f. Form

    Int append(Image img)Adds an item consisting of one Image to the

    Form.

    Int append(Item item)Adds an Item into the Form.

    Int append(String str)Adds an item consisting of one String to the

    Form.

    Item get(int itemNum)Gets the item at given position.

    Int getHeight()Returns the height in pixels of the displayable

    area available for items.

    int getWidth()

    Returns the width in pixels of the displayablearea available for items.

    void set(int itemNum, Item item)Sets the item referenced by itemNum to the

    specified item, replacing the previous item.

    void setItemStateListener(ItemStateListeneriListener)Sets the ItemStateListenerfor the Form, replacing

    any previous ItemStateListener.

    int size()Gets the number of items in the Form.

    g. Choice

    int append(String stringPart, Image imagePart)Appends an element to the Choice.

    int getSelectedFlags(boolean[] selectedArray_return)

  • 8/3/2019 Mobile Computing Pracs

    5/30

    M.Sc CS Part I J2ME

    5

    Queries the state of a Choice and returns thestate of all elements in the boolean arrayselectedArray_return.

    int getSelectedIndex()Returns the index number of an element in

    the Choice that is selected.

    String getString(int elementNum)Gets the String part of the element referenced

    by elementNum.

    boolean isSelected(int elementNum)Gets a boolean value indicating whether this

    element is selected.

    void setFont(int elementNum, Font font)Sets the application's preferred font for

    rendering the specified element of this Choice.

    int size()Gets the number of elements present.

    h. ChoiceGroup

    int getSelectedFlags(boolean[] selectedArray_return)Queries the state of a ChoiceGroup and returns

    the state of all elements in the boolean array

    selectedArray_return.

    int getSelectedIndex()Returns the index number of an element in the

    ChoiceGroup that is selected.

    String getString(int elementNum)Gets the String part of the element referenced

    by elementNum.

    boolean isSelected(int elementNum)Gets a boolean value indicating whether this

    element is selected.

    int size()Returns the number of elements in the

    ChoiceGroup.

    i. CommandListener

  • 8/3/2019 Mobile Computing Pracs

    6/30

    M.Sc CS Part I J2ME

    6

    void commandAction(Command c, Displayable d)Indicates that a command event has occurred

    on Displayable d.

    j. ItemStateListener

    void itemStateChanged(Item item)Called when internal state of an Item has been

    changed by the user.

    k. Runnable

    void run()

    When an object implementing interfaceRunnable is used to create a thread, starting thethread causes the object's run method to be called inthat separately executing thread.

    l. TimeTask

    boolean cancel()Cancels this timer task.

    abstract voidrun

    () The action to be performed by this timer task.

    long scheduledExecutionTime()Returns the scheduledexecution time of the

    most recent actualexecution of this task.

    m. Timer

    void cancel()Terminates this timer, discarding any currently

    scheduled tasks.

    void schedule(TimerTask task, Date time)Schedules the specified task for execution at

    the specified time.

    void schedule(TimerTask task, Date firstTime, long period)Schedules the specified task for repeated

  • 8/3/2019 Mobile Computing Pracs

    7/30

    M.Sc CS Part I J2ME

    7

    fixed-delay execution, beginning at the specifiedtime.

    void schedule(TimerTask task, long delay)Schedules the specified task for execution

    after the specified delay.

    void schedule(TimerTask task, long delay, long period)Schedules the specified task for repeated

    fixed-delay execution, beginning after the specifieddelay.

    void scheduleAtFixedRate(TimerTask task, Date firstTime,long period)

    Schedules the specified task for repeatedfixed-rate execution, beginning at the specified time.

    void scheduleAtFixedRate(TimerTask task, long delay,long period)

    Schedules the specified task for repeatedfixed-rate execution, beginning after the specifieddelay.

  • 8/3/2019 Mobile Computing Pracs

    8/30

    M.Sc CS Part I J2ME

    8

    Practical 1

    Topic: Create an application to draw simple text hello world.

    Code:

    import javax.microedition.lcdui.*;import javax.microedition.midlet.MIDlet;public class HelloWorld extends MIDlet implements CommandListener{ private Display display;

    private Command cmdexit;private TextBox txtmsg;public HelloWorld(){

    display=Display.getDisplay(this);cmdexit=new Command("Exit",Command.EXIT,0);txtmsg=new TextBox("Hello World","Hello World!",15,131072);

    }public void startApp(){ txtmsg.addCommand(cmdexit);

    display.setCurrent(txtmsg);txtmsg.setCommandListener(this);

    }public void pauseApp(){ }public void destroyApp(boolean unconditional){

    cmdexit=null;txtmsg=null;display=null;

    }public void commandAction(Command c,Displayable d)

    {if(c==cmdexit){

    destroyApp(true);notifyDestroyed();

    }}

    }

  • 8/3/2019 Mobile Computing Pracs

    9/30

    M.Sc CS Part I J2ME

    9

    Output

  • 8/3/2019 Mobile Computing Pracs

    10/30

    M.Sc CS Part I J2ME

    10

    Practical 2

    Topic:Create an application to draw simple text and perform various

    operations:

    - Draw a simple text in a device screen.

    - Change the text color.- Changing the font style and font size of a displayed text.

    Code:

    import javax.microedition.midlet.*;import javax.microedition.lcdui.*;

    public class FontChange extends MIDlet implements CommandListener {private Form form;private Display disp;private Command exitt,sel;

    private TextField tf;private ChoiceGroup fs,col,sz;String fstyle[]={ "Bold", "Italic", "UnderLine"};String fsize[]={ "Small", "Medium", "Large"};String colr[]={"Red","Green","Blue"};int b,i,u,size,col1,col2,col3;String str;MyCanvas ob;

    public FontChange(){

    form = new Form("");tf = new TextField("Name", null, 30, TextField.ANY);form.append(tf);

    col = new ChoiceGroup("Colour", List.EXCLUSIVE,colr,null);form.append(col);fs = new ChoiceGroup("Font-Style",Choice.MULTIPLE,fstyle,null);form.append(fs);sz = new ChoiceGroup("Size",List.POPUP,fsize,null);form.append(sz);exitt = new Command("Exit", Command.EXIT, 1);sel = new Command("Select",Command.SCREEN,2);form.addCommand(exitt);form.addCommand(sel);form.setCommandListener(this);

    }

    public void startApp() {disp = Display.getDisplay(this);disp.setCurrent(form);

    }

    public void pauseApp() {}

    public void destroyApp(boolean unconditional) {

  • 8/3/2019 Mobile Computing Pracs

    11/30

    M.Sc CS Part I J2ME

    11

    }

    public void commandAction(Command c, Displayable d) {boolean ch[]=new boolean[3];fs.getSelectedFlags(ch);if(ch[0])

    b = Font.STYLE_BOLD;if(ch[1])b = Font.STYLE_ITALIC;if(ch[2])b = Font.STYLE_UNDERLINED;

    if(col.getSelectedIndex() == 0){

    col1 = 255;col2 = 0;col3 = 0;

    }else if(col.getSelectedIndex() == 1)

    {col1 = 0;

    col2 = 255;col3 = 0;

    }else if(col.getSelectedIndex() == 2)

    {col1 = 0;col2 = 0;col3 = 255;

    }

    if(sz.getSelectedIndex() == 0){

    size = Font.SIZE_SMALL;}

    else if(sz.getSelectedIndex() ==1){

    size = Font.SIZE_MEDIUM;}

    else if(sz.getSelectedIndex() ==2){

    size = Font.SIZE_LARGE;}

    if (c == exitt){

    destroyApp(false);notifyDestroyed();

    }if (c == sel)

    {str = tf.getString();ob = new MyCanvas(col1,col2,col3,str,size,b);disp.setCurrent(ob);

    }

    }}

  • 8/3/2019 Mobile Computing Pracs

    12/30

    M.Sc CS Part I J2ME

    12

    class MyCanvas extends Canvas{

    int c1,c2,c3,ff1,sz1,b1;String str1;MyCanvas(int col1, int col2, int col3, String str, int size, int b) {

    c1 = col1;c2 = col2;c3 = col3;str1 = str;sz1 = size;b1 = b;

    }

    protected void paint(Graphics g) {

    Font font = Font.getFont(Font.FACE_PROPORTIONAL, b1, sz1);g.setColor(255,255,255);

    g.fillRect(0,0,getWidth(),getHeight());g.setColor(c1,c2,c3);

    g.setFont(font.getFont(font.FACE_SYSTEM,b1,sz1));g.drawString(str1,0,0,0);//(str1,150,60,0);

    }}

  • 8/3/2019 Mobile Computing Pracs

    13/30

    M.Sc CS Part I J2ME

    13

    Output

  • 8/3/2019 Mobile Computing Pracs

    14/30

    M.Sc CS Part I J2ME

    14

    Practical 3

    Topic: Create an application to handle multiple forms.

    Every form must have a Command Button to navigate through the forms.

    Every form should have a textbox to accept the tourist info.Form1 :- Tourist (Name, Phone. No, City)

    Form2 :- Ask for a destination state (on selecting the state it should display its

    capital as default.

    Form3 :- Tourist Details from Form1 and Form2.

    Code:

    package MultiForm;

    import javax.microedition.lcdui.*;import javax.microedition.midlet.*;

    public class MultiForm extends MIDlet implements CommandListener,ItemStateListener{

    Form form1,form2,form3,form4;TextField tf1,tf2,tf3,tf4;ChoiceGroup lst1,lst2;Display disp;Command cmdback,cmdnext,cmdexit;

    String str[]=new String[6];String[]h1={"Grand Hayatt","J.W. Mariott","Trident"};String[]h2={"The Raj Palace","Jai Mahal Palace","Rambagh Palace","Hotel Jaipur Greens"};String[]h3={"Royal Orchid Central Ahmedabad","Lemon Tree Hotel, Ahmedabad","Hotel

    Accolade","Hotel Ritz Inn"};String[]h4={"Ista Amritsar","Hotel Grand Legacy","MK Hotel Amristar","Golden Tulip Amritsar"};String[] states = {"Maharashtra","Rajasthan","Gujrat","Punjab"};String[] capital={"Mumbai","Jaipur","Gandhinagar","Chandigarh"};

    public MultiForm(){form1 = new Form("Personal Information");form2 = new Form("States");

    tf1 = new TextField("Name :- ", "", 50, TextField.ANY);tf2 = new TextField("City :- ", "", 50, TextField.INITIAL_CAPS_SENTENCE);tf3 = new TextField("Contact :- ", "", 50, TextField.PHONENUMBER);

    lst2 = new ChoiceGroup("Hotel List",List.EXCLUSIVE);cmdback = new Command("Back", Command.BACK, 0);cmdnext = new Command("Next",Command.SCREEN,1);cmdexit = new Command("Exit", Command.EXIT, 2);

  • 8/3/2019 Mobile Computing Pracs

    15/30

    M.Sc CS Part I J2ME

    15

    disp = Display.getDisplay(this);form1.append(tf1);form1.append(tf2);form1.append(tf3);form1.addCommand(cmdexit);form1.addCommand(cmdnext);

    form1.setCommandListener(this);

    lst1 = new ChoiceGroup("State",Choice.POPUP,states,null);form2.append(lst1);tf4 = new TextField("Capital :- ", "", 50, TextField.UNEDITABLE);form2.append(tf4);form2.addCommand(cmdback);form2.addCommand(cmdnext);

    }

    public void startApp() {disp.setCurrent(form1);

    }

    public void pauseApp() {}

    public void destroyApp(boolean unconditional) {}

    public void commandAction(Command c, Displayable d) {

    if(c==cmdexit){

    destroyApp(false);notifyDestroyed();

    }

    if(d==form1){

    if(c==cmdnext){

    str[0]=tf1.getString();str[1]=tf2.getString();

    str[2]=tf3.getString();

    form2.setCommandListener(this);form2.setItemStateListener(this);//disp.setCurrent(ok,form2);disp.setCurrent(form2);

    }}if(d==form2){

    if(c==cmdnext)

  • 8/3/2019 Mobile Computing Pracs

    16/30

    M.Sc CS Part I J2ME

    16

    {form3 = new Form(str[4]);form3.append(lst2);form3.addCommand(cmdback);form3.addCommand(cmdnext);

    form3.setCommandListener(this);form3.setItemStateListener(this);disp.setCurrent(form3);

    }if(c==cmdback){

    disp.setCurrent(form1);}

    }if(d==form3){

    if(c==cmdnext)

    {str[5]=lst2.getString(lst2.getSelectedIndex());form4 = new Form(str[0]+" Entered Information.");form4.append("Personal Details :\n=====================\n");form4.append("Name :- "+str[0]);form4.append("\nCity :- "+str[1]);form4.append("\nContact Number :- "+str[2]);form4.append("\nState :- \n"+"=====================\n"+str[3]);form4.append("\nState Capital :- "+str[4]);form4.append("\nHotel to stay :- "+str[5]);form4.addCommand(cmdback);

    form4.addCommand(cmdexit);form4.setCommandListener(this);

    disp.setCurrent(form4);}

    if(c==cmdback){

    disp.setCurrent(form2);}

    }if(d==form4){

    if(c==cmdback)

    {disp.setCurrent(form3);

    }if(c==cmdexit){destroyApp(false);notifyDestroyed();

    }}

    }

  • 8/3/2019 Mobile Computing Pracs

    17/30

    M.Sc CS Part I J2ME

    17

    public void itemStateChanged(Item item) {tf4.setString(capital[lst1.getSelectedIndex()]);str[3]=states[lst1.getSelectedIndex()];str[4]=tf4.getString();if(lst1.getSelectedIndex()==0)

    {lst2 = new ChoiceGroup("Hotel List",List.EXCLUSIVE,h1,null);

    }if(lst1.getSelectedIndex()==1){

    lst2 = new ChoiceGroup("Hotel List",List.EXCLUSIVE,h2,null);}if(lst1.getSelectedIndex()==2){

    lst2 = new ChoiceGroup("Hotel List",List.EXCLUSIVE,h3,null);}if(lst1.getSelectedIndex()==3)

    {lst2 = new ChoiceGroup("Hotel List",List.EXCLUSIVE,h4,null);

    }

    }}

  • 8/3/2019 Mobile Computing Pracs

    18/30

    M.Sc CS Part I J2ME

    18

    Output

  • 8/3/2019 Mobile Computing Pracs

    19/30

    M.Sc CS Part I J2ME

    19

    Practical 4

    Topic: Create an application to demonstrate timers.

    Draw a filled rectangle.

    Change the color of the rectangle after the specified interval of time.And display a marquee text

    Code:

    import javax.microedition.midlet.*;import javax.microedition.lcdui.*;import java.util.*;

    public class TimeAni extends MIDlet{

    private Display display;

    private AnimationCanvas1 canvas;private Timer timer;private AnimateTimerTask1 timertask;

    public TimeAni(){

    display = Display.getDisplay(this);timer = new Timer();canvas = new AnimationCanvas1();timertask = new AnimateTimerTask1(canvas);timer.schedule(timertask, 0, 100);

    }

    public void startApp()

    {display.setCurrent(canvas);

    }

    public void pauseApp() {}

    public void destroyApp(boolean unconditional) {destroyApp(true);

    }public void exitMIDlet(){

    destroyApp(true);

    }}class AnimateTimerTask1 extends TimerTask{private AnimationCanvas1 canvas;

    public AnimateTimerTask1(AnimationCanvas1 canvas){this.canvas = canvas;}

    public final void run(){

  • 8/3/2019 Mobile Computing Pracs

    20/30

    M.Sc CS Part I J2ME

    20

    canvas.changeColor();canvas.repaint();}

    }

    class AnimationCanvas1 extends Canvas {private Random random;int red, green, blue,x=0;

    public AnimationCanvas1(){random = new java.util.Random();init();}

    protected void paint(Graphics g){g.setColor(red, green, blue);g.fillRect(0, 0,getWidth(), getHeight());g.setColor(255,255,255);g.drawString("Rituraj", x, getHeight()/2, 0);x++;

    if(x>getWidth()){x=0;}}

    private void init(){changeColor();}

    protected void changeColor(){red = (random.nextInt() >>> 1) % 256;green = (random.nextInt() >>> 1) % 256;blue = (random.nextInt() >>> 1) % 256;}

    }

  • 8/3/2019 Mobile Computing Pracs

    21/30

    M.Sc CS Part I J2ME

    21

    Output

  • 8/3/2019 Mobile Computing Pracs

    22/30

    M.Sc CS Part I J2ME

    22

    Practical 5

    Topic : Create an application to demonstrate the use of Buffer.

    Code:

    import javax.microedition.lcdui.* ;import javax.microedition.midlet.* ;

    public class Buff extends MIDlet{

    public Display d ;CircleCan ccan ;

    public Buff (){

    d = Display.getDisplay(this) ;

    ccan = new CircleCan(d , 30) ;}

    public void startApp(){

    d.setCurrent(ccan) ;}

    public void pauseApp()

    {}

    public void destroyApp(boolean b)

    {

    }

    public class CircleCan extends Canvas implements Runnable{

    Display disp ;

    Image img ;int seconds ;long startTime ;int degree = 360 ;

    public CircleCan(Display d , int sec){

    this.disp = d ;this.seconds = sec ;

    // CREATING A DOUBLE BUFFER IF NOTif(! isDoubleBuffered() && false)

    img = Image.createImage(getWidth() , getHeight()) ;startTime = System.currentTimeMillis() ;

  • 8/3/2019 Mobile Computing Pracs

    23/30

    M.Sc CS Part I J2ME

    23

    }

    public void paint(Graphics g){

    Graphics g2 = img == null ? g : img.getGraphics() ;g2.setGrayScale(100) ;

    g2.fillRect(0, 0, getWidth(), getHeight()) ;

    if(degree > 0){

    g2.setColor(200, 100, 100) ;g2.fillArc(0, 0, getWidth(), getHeight(), 0, degree) ;disp.callSerially(this) ;

    }

    g2.setGrayScale(0) ;g2.drawArc(0, 0, getWidth(), getHeight(), 0, 360) ;

    }

    public void run(){

    int div = (int)((System.currentTimeMillis() - startTime) / seconds) ;degree = 360 - (div*360) / 1000 ;repaint() ;

    }}

    }

  • 8/3/2019 Mobile Computing Pracs

    24/30

    M.Sc CS Part I J2ME

    24

    Output

  • 8/3/2019 Mobile Computing Pracs

    25/30

    M.Sc CS Part I J2ME

    25

    Practical 6

    Topic: Create an application to demonstrate Bouncing Ball.

    It should have a menu having start and stop buttons on it.

    Code:

    import java.util.*;import javax.microedition.midlet.*;import javax.microedition.lcdui.*;public class Bounce extends MIDlet {private Display display;private AnimationCanvas canvas;private Timer timer;private AnimateTimerTask timertask;

    public Bounce(){display = Display.getDisplay(this);

    timer = new Timer();canvas = new AnimationCanvas(this);timertask = new AnimateTimerTask(canvas);timer.schedule(timertask, 0, 100);}

    protected void startApp(){display.setCurrent(canvas);}

    protected void pauseApp(){}

    protected void destroyApp(boolean unconditional){notifyDestroyed();

    }

    public void exitMIDlet(){destroyApp(true);}

    }class AnimateTimerTask extends TimerTask{private AnimationCanvas canvas;

    public AnimateTimerTask(AnimationCanvas canvas){this.canvas = canvas;}

    public final void run(){if ((canvas.x_loc + canvas.radius + canvas.x_dir > canvas.getWidth()) ||(canvas.x_loc - canvas.radius + canvas.x_dir < -25)){canvas.x_dir = -canvas.x_dir;canvas.change_way++;}if ((canvas.y_loc + canvas.radius + canvas.y_dir > canvas.getHeight()) ||(canvas.y_loc - canvas.radius + canvas.y_dir < -25)){canvas.y_dir = -canvas.y_dir;canvas.change_way++;

  • 8/3/2019 Mobile Computing Pracs

    26/30

  • 8/3/2019 Mobile Computing Pracs

    27/30

    M.Sc CS Part I J2ME

    27

    Output

  • 8/3/2019 Mobile Computing Pracs

    28/30

    M.Sc CS Part I J2ME

    28

    Practical 7

    Topic: Create an application to demonstrate a simple Calculator.

    It should be able to perform the basic functions of addition, substraction,

    multiplication ,divide.

    Code:

    import javax.microedition.midlet.*;

    import javax.microedition.lcdui.*;public class Calculator extends MIDlet implements CommandListener{

    public Display display;TextField num1,num2,result;Form frm1;Command cmdAdd,cmdSub,cmdMul,cmdDivide,cmdClear,cmdExit;

    int n1,n2,res;public Calculator(){

    display=Display.getDisplay(this);

    frm1=new Form("Calculator");

    num1=new TextField("Enter the First number","0",20,TextField.NUMERIC);num2=new TextField("Enter the Second number","1",20,TextField.NUMERIC);

    result=new TextField("Result","",50,TextField.UNEDITABLE);cmdExit=new Command("Exit",Command.OK,1);cmdAdd=new Command("Add",Command.OK,2);cmdSub=new Command("Sub",Command.OK,3);

    cmdMul=new Command("Multiply",Command.OK,4);cmdDivide=new Command("Divide",Command.OK,5);cmdClear=new Command("Reset",Command.OK,6);

    }public void startApp(){

    display.setCurrent(frm1);frm1.append(num1);frm1.append(num2);frm1.append(result);frm1.addCommand(cmdAdd);frm1.addCommand(cmdSub);

    frm1.addCommand(cmdMul);frm1.addCommand(cmdDivide);

    frm1.addCommand(cmdClear);frm1.addCommand(cmdExit);frm1.setCommandListener(this);

    }public void pauseApp(){}

  • 8/3/2019 Mobile Computing Pracs

    29/30

    M.Sc CS Part I J2ME

    29

    public void destroyApp(boolean b){}public void commandAction(Command c,Displayable d){

    n1=Integer.parseInt(num1.getString());

    n2=Integer.parseInt(num2.getString());if(c==cmdClear){

    num1.setString("");num2.setString("");result.setString("");

    }if(c==cmdAdd){

    res=n1+n2;result.setString(""+res);

    }

    if(c==cmdSub){

    res=n1-n2;result.setString(""+res);

    }if(c==cmdMul){

    res=n1*n2;result.setString(""+res);

    }if(c==cmdDivide)

    {if(n2==0)

    {result.setString("Division by zero not allowed");

    }else{

    res=n1/n2;result.setString(""+res);

    }

    }

    if(c==cmdExit){

    destroyApp(true);notifyDestroyed();}

    }}

  • 8/3/2019 Mobile Computing Pracs

    30/30

    M.Sc CS Part I J2ME

    Output