Wednesday, May 4, 2011

What is Java 2 Micro Edition?



Java is known primarily as a server-side programming environment, centered around the technologies that make up the Java 2 Enterprise Edition (J2EE), such as Enterprise JavaBeans (EJBs), servlets, and JavaServer pages (JSPs). Early adopters of Java, however, will recall that it was originally promoted as a client-side application environment. In fact, Java was originally designed as a programming language for consumer appliances. Now Java is returning to its roots with Java 2 Micro Edition, or J2ME for short.



The Java 2 Platform
What we commonly refer to as "Java" is more formally known as the Java 2 Platform. The Java 2 Platform is split into three editions: Java 2 Standard Edition (J2SE), Java 2 Enterprise Edition (J2EE), and Java 2 Micro Edition (J2ME). Each edition of the platform provides a complete environment for running Java-based applications, including the Java virtual machine (VM) and runtime classes.

Java 2 Micro Edition
In J2ME, the Java runtime environment is adapted for constrained devices - devices that have limitations on what they can do when compared to standard desktop or server computers. For low-end devices, the constraints are fairly obvious: extremely limited memory, small screen sizes, alternative input methods, and slow processors. High-end devices have few, if any, of these constraints, but they can still benefit from the optimized environments and new programming interfaces that J2ME defines.

Monday, May 2, 2011

J2ME Thread Processing Example



              
          


In the given example, you will learn about the thread and how thread works in
J2ME application. An application can run multiple activities simultaneously
using thread. Here we have defined different states of thread...

 The states of Thread is:

  • running:- Executing code.
  • ready:- Ready to execute code.
  • suspended:- Waiting on an external event. 
  • terminated:- Finished executing code.

In the output First of all process() thread will be executed then start()
thread and then run() thread will be executed.

The Application is as follows:

 

Source Code of ThreadProcessing.java 

 




import java.io.*;

import javax.microedition.io.*;

import javax.microedition.lcdui.*;

import javax.microedition.midlet.*;



public class ThreadProcessing extends MIDlet implements CommandListener{

  private Display display;

  private Ticker ticker;

  private Form form; 

  private Command exit, start;



  public ThreadProcessing(){

    form = new Form("Thread Processing");

    ticker = new Ticker ("10/17/2008 3:59:59 PM     ACC LTD 489.05 (-6.42%)

       BHARTI ARTL 676.80 (-7.47%)       BHEL 1,194.80 (-9.00%)

       ACC LTD 489.05 (-6.42%)    BHARTI ARTL 676.80 (-7.47%)

       BHEL 1,194.80 (-9.00%)       DLF LTD* 291.30 (-10.34%)

       GRASIM INDUSTRIES LTD. 1,293.40 (-5.71%)       HDFC BANK LT 1,024.05 (-5.82%)"
);

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

    start = new Command("Start", Command.SCREEN, 2);    

  }



  public void startApp(){

    display = Display.getDisplay(this);

    form.addCommand(exit);

    form.addCommand(start );    

    form.setCommandListener(this);

    form.setTicker(ticker);

    display.setCurrent(form);

  }



  public void pauseApp(){ }



  public void destroyApp(boolean unconditional){

    notifyDestroyed();

  }



  public void commandAction(Command c, Displayable displayable){

    String label = c.getLabel();

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

      destroyApp(false);

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

      Process process = new Process(this);

      process.start()

    

  }

}



class Process implements Runnable{

  private ThreadProcessing MIDlet;



  public Process(ThreadProcessing MIDlet){ 

    this.MIDlet = MIDlet;

    System.out.println("Thread Process...");

  }



  public void run(){

    try{

      transmit();

      System.out.println("Thread Run...");

    }catch(Exception error){ 

      System.err.println(error.toString());

    }      

  }



  public void start(){

    Thread thread = new Thread(this);

    try{

      thread.start();

      System.out.println("Thread Start...");

    }catch(Exception error){}

  }



  private void transmit() throws IOException{} 



}


 

Output:

 

Download Source Code

J2ME Thread Processing Example



              
          


In the given example, you will learn about the thread and how thread works in
J2ME application. An application can run multiple activities simultaneously
using thread. Here we have defined different states of thread...

 The states of Thread is:

  • running:- Executing code.
  • ready:- Ready to execute code.
  • suspended:- Waiting on an external event. 
  • terminated:- Finished executing code.

In the output First of all process() thread will be executed then start()
thread and then run() thread will be executed.

The Application is as follows:

 

Source Code of ThreadProcessing.java 

 




import java.io.*;

import javax.microedition.io.*;

import javax.microedition.lcdui.*;

import javax.microedition.midlet.*;



public class ThreadProcessing extends MIDlet implements CommandListener{

  private Display display;

  private Ticker ticker;

  private Form form; 

  private Command exit, start;



  public ThreadProcessing(){

    form = new Form("Thread Processing");

    ticker = new Ticker ("10/17/2008 3:59:59 PM     ACC LTD 489.05 (-6.42%)

       BHARTI ARTL 676.80 (-7.47%)       BHEL 1,194.80 (-9.00%)

       ACC LTD 489.05 (-6.42%)    BHARTI ARTL 676.80 (-7.47%)

       BHEL 1,194.80 (-9.00%)       DLF LTD* 291.30 (-10.34%)

       GRASIM INDUSTRIES LTD. 1,293.40 (-5.71%)       HDFC BANK LT 1,024.05 (-5.82%)"
);

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

    start = new Command("Start", Command.SCREEN, 2);    

  }



  public void startApp(){

    display = Display.getDisplay(this);

    form.addCommand(exit);

    form.addCommand(start );    

    form.setCommandListener(this);

    form.setTicker(ticker);

    display.setCurrent(form);

  }



  public void pauseApp(){ }



  public void destroyApp(boolean unconditional){

    notifyDestroyed();

  }



  public void commandAction(Command c, Displayable displayable){

    String label = c.getLabel();

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

      destroyApp(false);

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

      Process process = new Process(this);

      process.start()

    

  }

}



class Process implements Runnable{

  private ThreadProcessing MIDlet;



  public Process(ThreadProcessing MIDlet){ 

    this.MIDlet = MIDlet;

    System.out.println("Thread Process...");

  }



  public void run(){

    try{

      transmit();

      System.out.println("Thread Run...");

    }catch(Exception error){ 

      System.err.println(error.toString());

    }      

  }



  public void start(){

    Thread thread = new Thread(this);

    try{

      thread.start();

      System.out.println("Thread Start...");

    }catch(Exception error){}

  }



  private void transmit() throws IOException{} 



}



 

Output:

 

Download Source Code

J2ME Ticker Example

This is the simple Ticker example which is used to auto scroll the data on
the top of the form. It continuously scroll the data. The javax.microedition.lcdui.Ticker
has only one constructor that is:



Ticker(String str):- This is used to Constructs a new Ticker object,
given its initial contents string.

And it has two methods:

getString():- This is the String type methods which Gets the string
currently being scrolled by the ticker.

setString(String str):- This is the void type, it Sets the string to
be displayed by this ticker.

 

The Application looked as below:

 

Source Code of TickerExample.java 






import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;



public class TickerExample extends MIDlet implements CommandListener{

  private Display display; 

  private Ticker ticker; 

  private Command exit;

  private Form form;

    

  public TickerExample(){

    form = new Form("BSE Stock Exchange Ticker");

    display = Display.getDisplay(this);

    ticker = new Ticker ("10/17/2008 3:59:59 PM     ACC LTD 489.05 (-6.42%)     

      BHARTI ARTL 676.80 (-7.47%)       BHEL 1,194.80 (-9.00%)  

      ACC LTD 489.05 (-6.42%)  BHARTI ARTL 676.80 (-7.47%)       

      BHEL 1,194.80 (-9.00%)       DLF LTD* 291.30 (-10.34%)       

      GRASIM INDUSTRIES LTD. 1,293.40 (-5.71%)       

      HDFC BANK LT 1,024.05 (-5.82%)"
);

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

    form.addCommand(exit);

    form.setCommandListener(this);

    form.setTicker(ticker);

  }



  public void startApp(){

    display.setCurrent(form);

  }



  public void pauseApp(){ }



  public void destroyApp(boolean unconditional){

    notifyDestroyed();

  }



  public void commandAction(Command c, Displayable display){

    String label = c.getLabel();

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

      destroyApp(false);

    }

  }

}





Download Source Code

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

Search This Blog

Total Pageviews