Friday, April 29, 2011

Creating Multiple Type List

This example is shows how to create the list which has multiple type choice
option. In this example user can make selection in name list and after selection
application will display message according to the selection. Like..........



 

Sandeep: selected


Kumar: selected

Suman: not selected

 

 

The MULTIPLE keyword is used to create the multiple type list as
follows:

list = new List("Multiple Option", List.MULTIPLE);

The application look like as follows:

 



Source Code Of MultipleList.java
 





import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;




public class MultipleList extends MIDlet implements CommandListener{

  private Display display;

  private Command exit,view;     


  private List list;       



  public MultipleList(){

    exit = new Command("Exit", Command.EXIT, 1);


    view = new Command("View", Command.SCREEN,2);

  }



  public void startApp(){


    display = Display.getDisplay(this);

    list = new List("Multiple Option", List.MULTIPLE);


    list.append("Sandeep"null);

    list.append("Kumar"null);

    list.append("Suman"null);


    list.addCommand(exit);

    list.addCommand(view);

    list.setCommandListener(this);   


    display.setCurrent(list);

  }



  public void pauseApp(){ }



  public void destroyApp(boolean unconditional){


    notifyDestroyed();

  }



  public void commandAction(Command c, Displayable s){


    String label = c.getLabel();

    if (label.equals("View")){

      boolean selected[] new boolean[list.size()];


      list.getSelectedFlags(selected);

      for (int i = 0; i < list.size(); i++)


        System.out.println(list.getString(i(selected[i

                           
": selected" ": not selected"));


    }else if (label.equals("Exit")){

      destroyApp(false);      

    


  }

}




Output:

Download Source Code

Creating Menu Using Canvas Class

This example shows how to create the menu and call the canvas class to show
the toggle message. The Toggle message will appear when user perform some action
like click on a button ("Show"). In this example we have used the
following method:

  • setColor()
  • fillRect()
  • getWidth()
  • getHeight()
  • getFont()
  • fontHeight()
  • fontWidth()
  • setFont()
  • drawString()
  • repaint()

The repaint() method is used to appear the string on Canvas form.

The application look like as follows:

 




Source Code For CanvasMenu.java




import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;




public class CanvasMenu extends MIDlet implements CommandListener{

  CanvasString canvas;

  private Command exit;

  private Command toggle;




  public CanvasMenu() {

    canvas = new CanvasString();

  }



  public void startApp() throws MIDletStateChangeException {


    Display.getDisplay(this).setCurrent(canvas);

    exit = new Command("Exit", Command.EXIT, 7);

    toggle = new Command("Show", Command.SCREEN, 1);


    canvas.addCommand(exit);

    canvas.addCommand(toggle);

    canvas.setCommandListener(this);

    canvas.repaint();

  }



  public void destroyApp(boolean unconditional){


    notifyDestroyed();

  }



  public void pauseApp(){}



  public void commandAction(Command c, Displayable s){


    String label = c.getLabel();

    if(label.equals("Show")){

      canvas.toggleString();

    else if(label.equals("Exit")) {


      destroyApp(false);

    }

  }

}



class CanvasString extends Canvas {


  boolean string = true;

  void toggleString() {

    string = !string;

    repaint();

  }




  public void paint(Graphics g) {    

    g.setColor(0xccff66);

    g.fillRect(00, getWidth(), getHeight());


    if(string) {

      Font font = g.getFont();

      int fontHeight = font.getHeight();

      int fontWidth = font.stringWidth("This is the Toggle Message");


      g.setColor(2230112);

      g.setFont(font);

      g.drawString("This is the Toggle Message", (getWidth()-fontWidth)/2,


      (getHeight()-fontHeight)/
2, g.TOP|g.LEFT);

    }

  }

}





Download Source Code

 

J2ME Canvas Example

A J2ME Game Canvas Example

This example illustrates how to create a game using GameCanvas class.
In this example we are extending GameCanvas class to draw the circle and
rotate the circle continuously. The GameCanvas class has following
methods:

  • flushGraphics():- This is the void type method, it flushes to
    display on the off-screen buffer.
  • flushGraphics(int x, int y, int width, int height):- This is the
    void type method, it flushes to display of specified region on the
    off-screen buffer. 
  • getGraphics():- This is used to get the graphics objects.
  • getKeyStates():- This is the integer type variable, it is used to
    find the states of the key. 
  • paint(Graphics g):- This is also the void type method, it is used
    to paint the canvas. 


Other commands, input event, etc  methods inherited from Canvas class.
The Canvas class has following methods:

  • getGameAction(int keyCode) 
  • getHeight()
  • getKeyCode(int gameAction) 
  • getKeyName(int keyCode)
  • getWidth()
  • hasPointerEvents()
  • hasPointerMotionEvents() 
  • hasRepeatEvents()
  • hideNotify() 
  • isDoubleBuffered()
  • keyPressed(int keyCode) 
  • keyReleased(int keyCode) 
  • keyRepeated(int keyCode) 
  • paint(Graphics g)
  • pointerDragged(int x, int y) 
  • pointerPressed(int x, int y) 
  • pointerReleased(int x, int y) 
  • repaint() 
  • repaint(int x, int y, int width, int height) 
  • serviceRepaints() 
  • showNotify()

 


Source Code of CanvasGame.java







import javax.microedition.lcdui.*;

import javax.microedition.lcdui.game.*;

import javax.microedition.midlet.*;



public class CanvasGame extends MIDlet{




  private Command back;

  private Display display;

  final SweepGame game = new SweepGame();




  public void startApp() {

    back = new Command("Back", Command.BACK, 0);

    game.start();

    game.addCommand(back);


    game.setCommandListener(new CommandListener(){

      public void commandAction(Command c, Displayable s) {

        game.stop();

        notifyDestroyed();

      }


    });

    display = Display.getDisplay(this);

    display.setCurrent(game);

  }



  public void pauseApp() {}




  public void destroyApp(boolean unconditional) {}

}



class SweepGame extends GameCanvas implements Runnable {


  private boolean move;

  private int radius;

  private int diameter;

  private int interval;




  public SweepGame() {

    super(true);

    radius = 0;

    diameter = 10;


    interval = 0;

  }

  public void start() {

    move = true;

    Thread t = new Thread(this);


    t.start();

  }

  public void stop() {

    move = false;

  }

  public void render(Graphics g) {


    int width = getWidth();

    int height = getHeight();

    g.setColor(183,251,121);

    g.fillRect(0, 0, width - 1, height - 1);


    int x = diameter;

    int y = diameter;

    int w = width - diameter * 2;


    int h = height - diameter * 2;

    for (int i = 0; i < 17; i=i+2) {


      g.setColor(((17 - i) * 15 - 7),20,((17 - i) * 15 - 7));

      g.fillArc(x, y, w, h, radius + i * 10, 10);


      g.fillArc(x, y, w, h, (radius + 180) % 360 + i * 10, 10);

    }


  }

  public void run() {

    Graphics g = getGraphics();

    while (move) {

      radius = (radius + 1) % 360;


      render(g);

      flushGraphics();

      try {

        Thread.sleep(interval);

      }

      catch (InterruptedException ie) {}

    }


  }

}





Download Source Code

List in J2ME

Exclusive List MIDlet Example

This example illustrates how to create a Exclusive List. The Exclusive List
is used to select only one list element at a time. The EXCLUSIVE Field
inherited from interface javax.microedition.lcdui.Choice. There are three
choices in this interface, that are:

  • EXCLUSIVE 
  • IMPLICIT 
  • MULTIPLE

The one line code of Exclusive Choice is as follows:

list = new List("Movies", Choice.EXCLUSIVE)

In the next example, you will see how to use implicit choice list 


The EXCLUSIVE List Look like as follows:

 




Source Code Of ExclusiveChoiceList.java

 




import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;



public class ExclusiveChoiceList extends MIDlet{


  private Display display;

  private List list;



  public ExclusiveChoiceList() {

    list = new List("Movies", Choice.EXCLUSIVE);


  }



  public void startApp(){

    display = Display.getDisplay(this);

    list.append("The Legend of Bhagat Singh"null);


    list.append("Mother India"null);

    list.append("Lagaan"null);


    list.append("Chak De.."null);

    list.append("Hum Aapke Hain Kaun"null);


    display.setCurrent(list);

  }



    public void pauseApp() {}



    public void destroyApp(boolean unconditional){


    notifyDestroyed();

  }

}





 

Download Source Code

Thursday, April 28, 2011

J2ME List Image

List Image MIDlet Example

This example illustrates how to create list with image symbol. In this
example we are trying to create list using of List class. The List class define
in two type of constructors, that is:




  • List(String title, int listType)
  • List(String title, int listType, String[] stringElements, Image[]
    imageElements)
     

The List class has following Methods:

  • append(String stringPart, Image imagePart):- This method is the
    integer type, which is used to append an element to the choice. 
  • delete(int elementNum):- This is the void type which deletes the
    element. 
  • getImage(int elementNum):- This is the Image type which gets the
    image.
  • getSelectedFlags(boolean[] selectedArray_return):- This is integer
    type method which has the state of a Choice and returns the state of all
    elements in the boolean array. 
  • getSelectedIndex():- This is the integer type which returns the
    index number of an element in the Choice that is selected. 
  • getString(int elementNum):- This method is used to get the String
    of the element.
  • insert(int elementNum, String stringPart, Image imagePart):- This
    is void type it inserts an element into the Choice just prior to the element
    specified. 
  • isSelected(int elementNum):- It gets the boolean value indicating
    whether element is selected or not. 
  • set(int elementNum, String stringPart, Image imagePart):- It sets
    the element to the specified element, replacing the previous contents of the
    element. 
  • setSelectedFlags(boolean[] selectedArray)
  • setSelectedIndex(int elementNum, boolean selected)
  • size()

The SELECT_COMMAND is used to recognized whether user select from list
or not.


 

 

 





Source Code of ListImage.java 

 




import java.io.IOException;

import javax.microedition.lcdui.*;

import javax.microedition.midlet.*;



public class ListImage extends MIDlet implements CommandListener{


  private Display display;

  private List list;

  private Command exit, next;

  private Image car, airplane, hotel, mobile, cartoon;


  String[] stringElements = {"Aero plane""Car""Hotel""Mobile"};

  


  public ListImage(){

    try{

      airplane = Image.createImage("/airplane.png");

      car = Image.createImage("/car1.png");


      hotel = Image.createImage("/hotel1.png");

      mobile = Image.createImage("/mobile_ico.png");

      cartoon = Image.createImage("/cartoon.png");


    }catch(Exception e){

      System.err.println(e.getMessage());

    }

  }




  public void startApp() {

    display = Display.getDisplay(this);

    Image[] imageElements = {airplane, car, hotel, mobile};


    list = new List("List + Image", List.IMPLICIT, 

stringElements, imageElements
);





    next = new Command("Select", Command.SCREEN, 0);

    exit = new Command("Exit", Command.EXIT, 0);


    list.addCommand(next);

    list.addCommand(exit);

    list.setCommandListener(this);


    display.setCurrent(list);

  }



  public void pauseApp() {}



  public void destroyApp(boolean unconditional){


    notifyDestroyed();

  }



  public void commandAction(Command c, Displayable s){


    int index = list.getSelectedIndex();

    if (c == next || c == List.SELECT_COMMAND) {


      Alert alert = new Alert("Selected""You have selected: 

+ list.getString(index






        + 
".", cartoon, AlertType.INFO);

      display.setCurrent(alert, list);


    else if(c == exit){

      destroyApp(true);

    }


  }

}





 

Download Source Code

J2ME Contact List

This Example goes to create a Phone Book MIDlet


This example illustrates how to create your phone book. In this example
we are taking three SCREEN button ("Next", "New",
"Exit")
and taking two TextBox ("name",

"number").
In the name field user enters name and in number field
user enters phone number. When user enters name and click on Next button then
number text box will open, now user enters phone number. In case user
select  "Exit" or  "New" the name and number
get prints on the console. 

When
program will run initially, startApp() method will be called. And both

"Enter Name" text box and the "Next" button will be
displayed. After that if user clicks on next button the commandAction() method
will be called that will check, if label is equal to "Next" then number TextBox
will appear on the screen that can be used to enter the phone number of
user. 




 


The application display as below:

 

 

 

Source code of PhoneBookExample.java

 




import javax.microedition.lcdui.*;

import javax.microedition.midlet.*;



public class PhoneBookExample extends MIDlet implements CommandListener {


  private Command exit, next, New;

  private TextBox name, number;

  private Display display;

  private String nam, no;


  private Form form;

  

  public PhoneBookExample(){

    next = new Command("Next", Command.SCREEN, 2);


    exit = new Command("Exit", Command.SCREEN, 2);

    New = new Command("New", Command.SCREEN, 2);


  }



  public void startApp(){

    display = Display.getDisplay(this);

    name = new TextBox("Enter Name"""30, TextField.ANY);


    name.addCommand(next);

    name.setCommandListener(this);

    number = new TextBox("Enter Number"""13, TextField.PHONENUMBER);


    number.addCommand(New);

    number.addCommand(exit);

    number.setCommandListener(this);


    display.setCurrent(name);

  }



  public void pauseApp() {}



  public void destroyApp(boolean unconditional){


    notifyDestroyed();

  }



  public void commandAction(Command c, Displayable s){


    String label = c.getLabel();

    if (label.equals("Exit")){

      nam = name.getString();


      no = number.getString();

      System.out.println("Name = " + name.getString() ", 

      Number = "
+ number.getString());


      destroyApp(false);

    else if (label.equals("Next")){

      number.setString("");


      display.setCurrent(number);

    else if (label.equals("New")){

      display.setCurrent(name);


      nam = name.getString();

      no = number.getString();

      System.out.println("Name = " + name.getString() ", 


      Number = "
+ number.getString());

      name.setString("");

    }

  }


}




 

Download Source Code

Creating MIDlet Application For Login in J2ME

This example show to create the Midlet application for user login.

Creating MIDlet Application For Login in J2ME

              
          


This example show to create the MIDlet application for user login . All
MIDlet applications for the MIDP ( Mobile Information Device Profile) derived
from  MIDlet class and it play a role as a mediator between the application
and the environment in which the application runs. The MIDlet life cycle manage the flow of application.
It is in the javax.microedition.midlet package, so import this
package in your application. The javax.microedition.icdui package is used
for following classes:

  • Alert
  • AlertType
  • Canvas
  • ChoiceGroup
  • Command
  • DateField
  • Display
  • Displayable
  • Font
  • Form
  • Gauge
  • Graphics
  • Image
  • ImageItem
  • Item
  • List
  • Screen
  • StringItem
  • TextBox
  • TextField
  • Ticker 



In this example we will create a MIDlet (LoginExample), that
will show following output display look like below: 


 

        

Click on 'Launch' Button then the login page display like below:

Give Your LoginID 'sandeep' and Password 'sandeep' then it call
the commandAction where if condition will be executed and it calls a
function (validateUser()) which checks whether name and password is equal
to 'sandeep' or not if it equal to 'sandeep' then it executed the showMsg()

function which show a congratulation message but if name and password
is not equal to 'sandeep' then it call tryAgain() function which
show the error page like figure below and it return on login page with refresh
value.

 

 


 

Source Code Of LoginExample.java



import javax.microedition.midlet.MIDlet;

import javax.microedition.lcdui.*;




public class LoginExample extends MIDlet implements CommandListener{

  private Display display;

  private TextField userName,password;


  public Form form;

  private Command login,cancel;

  private Image img, imge, img2;

      

  public LoginExample() {


    form = new Form("Sign in");

    userName = new TextField("LoginID:"""30, TextField.ANY);


    password = new TextField("Password:"""30, TextField.PASSWORD);

    cancel = new Command("Cancel", Command.CANCEL, 2);


    login = new Command("Login", Command.OK, 2);

    try{

      img = Image.createImage("/logo.png");


      imge = Image.createImage("/front_left1_bad.png");

      img2 = Image.createImage("/Congratulations-1.png");

    }catch(Exception e){


      System.out.println(e.getMessage());

    }    

  }



   public void startApp() {


    display = Display.getDisplay(this);

    try{form.append(img);}catch(Exception e){}


    form.append(userName);

    form.append(password);

    form.addCommand(cancel);


    form.addCommand(login);

    form.setCommandListener(this);

    display.setCurrent(form);


  }



  public void pauseApp() {}



  public void destroyApp(boolean unconditional) {


    notifyDestroyed();

  }



  public void validateUser(String name, String password) {


    if (name.equals("sandeep"&& password.equals("sandeep")) {

      showMsg();

    else {


      tryAgain();

    }

  }  



  public void showMsg() {

    Alert success = new Alert("Login Successfully"


    "Your Login Process is completed!"


     img2, AlertType.INFO
);

    success.setImage(img2);


    userName.setString("");

    password.setString("");

    display.setCurrent(success, form);    


  }



  public void tryAgain() {

    Alert error = new Alert("Login Incorrect""Please 


    try again"
, imge, AlertType.ERROR);

    error.setTimeout(900);

    error.setImage(imge);


    userName.setString("");

    password.setString("");

    display.setCurrent(error, form);


  }

  

  public void commandAction(Command c, Displayable d) {

    String label = c.getLabel();


    if(label.equals("Cancel")) {

      destroyApp(true);

    else if(label.equals("Login")) {


      validateUser(userName.getString(), password.getString());

    

  }

}



 

Download Source Code

Source code of 'jad' and 'properties' file

Java Application Descriptor (JAD) filename extension is .jad and media
type is text/vnd.sun.j2me.app-descriptor, which developed by the Sun
Microsystems, Inc. The JAD file is used for java or games application. The java
application enabled mobile phone connected programmatically with online Web
Services. Through this facility we can send SMS via GSM mobile Internet.                     


 


 


 


 


 


Tutorials.jad

MIDlet-1: LoginExample, , LoginExample

MIDlet-Jar-Size: 4165

MIDlet-Jar-URL: LoginPage.jar

MIDlet-Name: LoginPage


MIDlet-Vendor: Unknown

MIDlet-Version: 1.0

MicroEdition-Configuration: CLDC-1.0

MicroEdition-Profile: MIDP-1.0

 

The jad file formate is as follows:          




MIDlet-1:  <Application name>, <icon path>,
<midlet class>
MIDlet-Jar-Size: <Size in bytes>
MIDlet-Jar-URL: <Associated JAR file>
MIDlet-Name: <Application name>
MIDlet-Vendor: <Company>
MIDlet-Version: <Application version number>
MicroEdition-Configuration: <CLDC version>
MicroEdition-Profile: <MIDP version>

 

Source code of project.properties is as follows:

JSR082: false

JSR172: true


JSR184: false

JSR75: false

MMAPI: true

WMA2.0: false

configuration: CLDC1.0

platform: JTWI

 

Source code of MANIFEST.MF is as follows:

MIDlet-1: LoginExample, , LoginExample

MIDlet-Name: LoginPage


MIDlet-Vendor: Unknown

MIDlet-Version: 1.0

MicroEdition-Configuration: CLDC-1.0

MicroEdition-Profile: MIDP-1.0

Download Source Code

Java Plateform Micro Edition

Java
ME was designed by Sun Microsystems and is a replacement for a similar
technology, Personal Java. Originally developed under the Java Community
Process as JSR 68, the different flavors of Java ME have evolved in
separate JSRs. Sun provides a reference implementation of the
specification, but has tended not to provide free binary implementations
of its Java ME runtime environment for mobile devices, rather relying on
third parties to provide their own. As of 22 December 2006, the Java ME
source code is licensed under the GNU General Public License, and is
released under the project name phone.

Java
ME has become a popular option for creating games for cell phones, as they
can be emulated on a PC during the development stage and easily uploaded
to the phone. This contrasts with the difficulty of developing, testing,
and loading games for other special gaming platforms such as those made by
Nintendo, Sony, Microsoft, and others, as expensive system-specific
hardware and kits are required.


Usage of Java ME

Java
ME includes flexible user interfaces, robust security, built-in network
protocols, and support for networked and offline applications that can be
downloaded dynamically. Applications based on Java ME are portable across
many devices; yet leverage each device?s native capabilities.

Java
ME device as implement a profile, the most common of these are the Mobile
Information Device Profile aimed at mobile devices, such as cell phones,
and the Personal Profile aimed at consumer products and embedded devices
like Set-top boxes and PDAs.


Developing with Java ME

Writing
a Java ME application uses the same basics programming constructs as used
with Java SE applications. Basically there are two types of configurations
involved in Java ME application development, which are:

CLDC
(Connected Limited Device Configuration)

CDC (Connected
Device Configuration)

Architecture
The Java ME Architecture comprises of three software layers:

The
first layer is the configuration layer that includes the JVM, which
directly interacts with the native OS. The Configuration layer also
handles the interaction between the profile and the JVM.



The second layer is the profile layer, which consists of the minimum set
of application programming interface (API) for the small devices.

The
third layer is the Mobile Information Device profile (MIDP) layer. The
MIDP layer contains java APIs for user network connections, persistence
storage, and the user interface. It also has access to CLDC libraries and
MIDP libraries.



The Java ME Application Development


I.
System Requirements - Hardware


Minimum hardware requirements are:


  • 100
    MB hard disk space



  • 128
    MB system RAM


  • 800
    MHz Pentium III CPU

II.
Minimal Software Requirement


  • IDE
    ? Sun ONE Studio 4, Mobile Edition,

    (formerly Forte for Java)


  • GUI
    ? Sun Java ME Wireless Toolkit 2.5.1 (WTK 2.5.1) for CLDC

For Windows:
Download the Sun Java Wireless Toolkit for CLDC from
http://java.sun.com/products/ s j w t o o l k i t / d o w n l o a d. h t m
l Ensure that you have installed an appropriate


Java SE environment.
Run the installer, sun_java_wireless_toolkit- 2_5_1-windows.exe. Follow
the instructions provided by the installer.




Download the Sun Java Wireless Toolkit for CLDC from
http://java.sun.com/products/ s j w t o o l k i t / d o w n l o a d . h t
m l Ensure that you have installed an appropriate

Java
SE environment



Run the installer, sun_java_wireless_toolkit- 2_5_1-linux.exe. Follow the
instructions provided by the installer.




III. install Sun Java ME Wireless Toolkit 2.5.1 (WTK 2.5.1) on the Windows
platform.




  • Download
    the installer file i.e. netbeans_mobility-5_5_1-win.exe


  • Double
    Click the icon of downloaded exe.


Now we are ready to create an application with Java Platform ME. Lets create a new project with the following steps:

Step 1: Go to Windows start panel and choose" Wireless Toolkit 2.5.1? as: Start > Programs > Sun Java Wireless Toolkit 2.5.1 for CLDC > Wireless Toolkit 2.5.1. The console window appears like this.

Step 2: Now, Click the ?New Project?
on the toolkit menu bar, then a new project box opens. Fill the appropriate Project name and
MIDlet class Name of your choice. After that, click Create Project button.

Step 3: Now, Click the ?New Project?
on the toolkit menu bar, then a new project box opens. Fill the appropriate Project name
(Roseindia)and MIDlet class Name(RoseindiaMID) of your choice. After that, click Create Project button.

Step 4: Then a ?Settings for project? window appears. For default settings, click OK. It is

Step 5: Next appears a window indicating the updated project settings saved in the Console.


Here is the code of this program:

import javax.microedition.lcdui.*; 

import javax.microedition.midlet.MIDlet; 
public class HelloWorld extends MIDlet implements CommandListener { 
public void startApp() { 
Display display = Display.getDisplay(this); 

Form mainForm = new Form("HelloWorld"); 

mainForm.append("Welcome to the world of Mobile"); 

Command exitCommand = new Command("Exit", Command.EXIT, 0); 

mainForm.addCommand(exitCommand); 

mainForm.setCommandListener(this); 

display.setCurrent(mainForm); 



public void pauseApp () {} 

public void destroyApp(boolean unconditional) {} 

public void commandAction(Command c, Displayable s) { 

if (c.getCommandType() == Command.EXIT) 

notifyDestroyed(); 



}

Download source code.

Step 6:

Now we need to develop a simplest "Hello World" program in the directory
structure in src folder.

Step 7:
Now, Click the ?Open Project? on the toolkit menu bar, 



Step 8:
Next click the ?Build? button from the toolkit menu bar. This causes the Sun Java Wireless Toolkit for CLDC to compile and preverify the Java source files. The whole build process is shown below.



Step 9:
Next click the ?Run? button from the toolkit menu bar. This executes the compiled Java class files on the emulator.




Step 10:

Output of project Roseindia at emulator is lick this



Step 11:
Execution of the compiled Java class files on the emulator gives the following customized output. This output window have



Output:
Hello World" program



Search This Blog

Total Pageviews