SlideShare a Scribd company logo
J2ME 1
Java 2 Platform, Micro Edition
(J2ME)
J2ME 2
Contents
• What’s J2ME?
• J2ME core concepts
– Configurations (CLDC, CDC)
– Profiles (MIDP)
• MIDlet, MIDlet Suite
• Basic classes API
• Installation and using the Toolkit
• Demos!!!
J2ME 3
Introduction
• Personalized and intelligent information appliances are
necessities in our life today.
• Such appliances can be:
– cell phones
– two-way pagers
– smart cards
– personal organizers
– palmtops
• These appliances tend to be special-purpose, limited-
resource, network-connected devices.
J2ME 4
Environment requirements
• We need an environment which is adapted for
constrained devices - devices that have limitations on
what they can do when compared to standard
desktop or server computers.
• The constraints are:
– extremely limited memory
– small screen sizes
– alternative input methods
– slow processors
J2ME 5
So – what’s the solution?
• Because of the vast
need, Sun has decided
to develop a special
edition of Java - J2ME
(Java 2 Micro Edition).
J2ME 6
Java Editions
• Different devices have different requirements
and different expectations of Java.
• One platform (solution) cannot address all the
market segments (web server, video games
etc.)
• Users/developers want flexibility. They want
to choose what they want to use and what
they do not.
J2ME 7
Java Editions
• The Java 2 Platform is split into three editions.
• Each edition provides a complete environment
for running Java-based applications, including
the Java virtual machine (VM) and runtime
classes.
• The three editions target different kinds of
applications running on different kinds of
devices.
J2ME 8
Java Editions
Java2
Standard Edition
(J2SE™)
Java2
Enterprise Edition
(J2EE™)
Java2
Micro Edition
(J2ME™)
Java 2 Platform
Standard desktop &
workstation applications
Heavy duty server
systems
Small & memory
constrained devices
J2ME 9
Java Editions
• Each edition defines different sets of class
libraries.
• There are thousands of core J2SE runtime
classes, taking up to 10-20 megabytes
of space.
• J2ME-based devices have
fewer classes.
J2ME
J2SE
J2EE
J2ME 10
PersonalJava and EmbeddedJava
• J2ME is not the first attempt at adapting Java
for constrained environments.
• PersonalJava
– Uses the basic Java 1.1 runtime classes with a few
features from Java 2.
– Implementation still requires a couple of
megabytes of memory and a fast processor to run.
J2ME 11
PersonalJava and EmbeddedJava
• EmbeddedJava
– Makes every behavior of the JVM and the runtime
classes optional - the implementor can choose
exactly which classes and methods are required.
– "write once, run anywhere".
J2ME 12
J2ME Core Concepts
• Configuration
– Minimum platform
required for a
group of devices
• Profile
– Addresses specific
needs of a certain
device family
• Optional Packages
J2ME
Profile/API
J2ME
Libraries
Java Virtual Machine
Host Operating System
Java Language
J2ME
MIDP
J2ME 13
J2ME Core Concepts
J2ME is based on 3 core concepts:
• Configurations
• Profiles
• Optional packages
J2ME 14
Configurations
• A configuration is a complete Java runtime
environment, consisting of:
– Java virtual machine (VM) to execute Java
bytecode
– Native code to interface to the underlying system
– Set of core Java runtime classes
• To use a configuration, a device must meet
certain minimum requirements.
J2ME 15
Configurations
• The set of core classes is normally quite small
and must be enhanced with additional classes
supplied by J2ME profiles or by configuration
implementor.
• Configurations do not define any user
interface classes.
J2ME 16
Configurations
Configuration
CLDC CDC
Connected Limited
Device Configuration
Connected Device
Configuration
J2ME 17
CLDC vs. CDC
• CLDC
– For very constrained
devices
– 160 - 512 KB of total
memory
– 16-bit or 32-bit
processor
– Low power
consumption and
often operating with
battery power
– Connectivity with
limited bandwidth
• CDC
– 2 MB or more memory
for Java platform
– 32-bit processor
– High bandwidth
network connection,
most often using
TCP/IP
J2ME 18
CLDC vs. CDC - VM
• Features missing in
the CLDC VM:
– Floating point types
– Object finalization
– JNI or reflection
– Thread groups or
daemon threads
– User Class loaders
• Change in classfile verification
 preverification
• The CDC supports a
complete, full-
featured Java 2 virtual
machine
J2ME 19
J2ME Core Concepts
J2ME is based on 3 core concepts:
• Configurations
• Profiles
• Optional packages
J2ME 20
Profiles
• Adds domain-specific classes to a configuration:
– To fill in missing functionality
– To support specific uses of a device
• Most profiles define user interface classes for
building interactive applications.
• To use a profile, the device must meet the minimum
requirements of the underlying configuration and of
the profile.
J2ME 21
Profiles
Profile
MIDP PDAP PP
PBP
FP
Mobile
Information
Device Profile
Personal
Digital
Assistant
Profile
Foundation
Profile
Personal Basis
Profile
Personal
Profile
J2ME 22
MIDP – MID Profile
• MIDP is targeted at a class of devices known
as mobile information devices (MIDs).
• Minimal characteristics of MIDs:
– Enough memory to run MIDP applications
– Display of at least 96 X 56 pixels, either
monochrome or color
– A keypad, keyboard, or touch screen
– Two-way wireless networking capability
J2ME 23
J2ME Core Concepts
J2ME is based on 3 core concepts:
• Configurations
• Profiles
• Optional packages
J2ME 24
Optional Packages
• Set of APIs in support of additional, common
behaviors.
• Have specific dependencies on a particular
configuration and/or one or more profiles.
• Examples of optional packages :
– RMI Optional Package
– Bluetooth Optional Package
– JDBC Optional Package
J2ME 25
What it all means
• "J2ME application" is an ambiguous term.
• Configuration, profile and optional packages should
be chosen.
• CDC-based profiles make development simpler due
to J2SE-like APIs, but don’t suit the low-end devices.
• CLDC-based profiles makes the development task
harder, especially when trying to shrink the size of
the application to run on many of the small devices.
J2ME 26
J2ME 27
MIDlets – The heart of J2ME…
• MIDP does not support the running of
applications that use a static main method as
their entry point, nor calling the System.exit
method in order to terminate.
• Instead, we use a MIDlet, which is a MID
Profile application.
J2ME 28
MIDlets – The heart of J2ME…
• Every application must extend
javax.microedition.midlet.MIDlet class to
allow the application management software
to:
– control the MIDlet
– be able to retrieve properties from the application
descriptor
– notify and request state changes
J2ME 29
MIDlets – The heart of J2ME…
• The extending class is the main class of the
application.
• The MIDlet class defines abstract methods
that the main class implements (for example:
startApp(), destroyApp(), notifyDestroyed()).
J2ME 30
MIDlet Suite
• One or more MIDlets are packaged together
into a MIDlet suite, composed of:
– JAR (Java archive) file
– JAD (Java Application Descriptor) file
• All the user-defined classes and resources
required by the suite's MIDlets must be in the
JAR file.
J2ME 31
MIDlet Suite
• The JAR file must also include a manifest that
describe the MIDlets in the suite.
• The application descriptor (JAD) contains
similar information, and is used by devices to
obtain information about a MIDlet suite
without having to download and install the
MIDlet suite first.
J2ME 32
Creating a MIDlet
J2ME 33
Creating a MIDlet
Importing MIDP
specific packages
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
J2ME 34
Creating a MIDlet
Extends MIDlet
Implements
CommandListener
public class HelloMIDlet
extends MIDlet
implements CommandListener {
J2ME 35
Creating a MIDlet
Creating the
form, adding the
Commands
public HelloMIDlet() {
mMainForm = new Form("HelloMIDlet");
mMainForm.append(new StringItem(null,
"Hello, Seminar Software Design!"));
mMainForm.addCommand(new Command("Exit",
Command.EXIT, 0));
mMainForm.setCommandListener(this);
}
J2ME 36
Sample MIDP classes API
• MIDlet
• Form
• Command
– CommandListener
– ItemCommandListener
• Item
J2ME 37
Sample classes API
• MIDlet – Base class
• Form
• Command
– CommandListener
– ItemCommandListener
• Item
J2ME 38
MIDlet class API
• protected abstract void startApp()
• protected abstract void pauseApp()
• protected abstract void
destroyApp(boolean unconditional)
• public final String
getAppProperty(String key)
• public final void notifyDestroyed()
J2ME 39
Sample classes API
• MIDlet
• Form
• Command
– CommandListener
– ItemCommandListener
• Item
J2ME 40
Form class
• A Form is a Screen that contains an arbitrary mixture
of items: images, read-only text fields, editable text
fields, editable date fields, gauges, choice groups,
and custom items.
• In general, any subclass of the Item class may be
contained within a form.
• The implementation handles layout, traversal, and
scrolling.
J2ME 41
Form class API
• Item management
–public int append(Item item)
–public Item get(int itemNum)
• Layout
• public void
setItemStateListener(ItemStateL
istener iListener)
J2ME 42
Sample classes API
• MIDlet
• Form
• Command
– CommandListener
– ItemCommadListener
• Item
J2ME 43
Command class
• The Command class represents the semantic
meaning of an action. Command objects are
presented in the user interface.
• The action itself is implemented in a
CommandListener object.
• The CommandListener is associated with a
Displayable or an Item.
• Once the Command is called – the CommandListener
is invoked, and the action is performed.
J2ME 44
Command class
• Command label
–public String getLabel()
• Command type
–public int getCommandType()
• Command priority
–public int getPriority()
J2ME 45
CommandListener class API
• This object is a listener for Commands that are
attached to a Displayable.
• public void
commandAction(Command c,
Displayable d)
J2ME 46
ItemCommandListener class API
• When a command (attached to an Item) is
invoked, the application is notified by having
the commandAction() method called on the
ItemCommandListener that had been set on
the Item.
• public void
commandAction(Command c,
Item item)
J2ME 47
Sample classes API
• MIDlet
• Form
• Command
– CommandListener
– ItemCommandListener
• Item
J2ME 48
Item class
• A superclass for components that can be
added to a Form.
• All Item objects have a label field
• Choose the Item’s layout, size, and
appearance
• Attach Commands
J2ME 49
Item class API
• public void
setDefaultCommand(Command cmd)
• public void
setItemCommandListener(ItemComm
andListener listener)
• public void
notifyStateChanged()
• public int getPreferredWidth()
J2ME 50
Getting Started…
–1st step: Download sun’s J2ME Wireless
Toolkit from:
http://java.sun.com/products/j2mewtoolkit/do
wnload-2_1.html
–2nd step: Make sure you have J2SE SDK
installed
–3rd step: Install the J2ME Toolkit.
J2ME-USER INTERFACE
User Interface
• A user interface is a set of routines that displays
information on the screen, prompts the user to
perform a task, and then processes the task.
• For example, a J2ME email application might display
a list of menu options, such as Inbox, Compose, and
Exit, and then prompt the user to make a selection by
moving the cursor keys and pressing a key on the
small computing device.
• The device’s application manager passes the
selection to the application, where it is compared with
known options.
User Interface (contd)
• Three kinds of user interfaces command, form, or canvas
• A command-based user interface consists of instances of the
Command class. For example, Exit ,Help
• A form-based user interface consists of an instance of the
Form class that contains instances derived from the Item class
such as text boxes, radio buttons, check boxes, lists etc to
display information on the screen and to collect input from the
user.
• A canvas-based user interface consists of instances of the
Canvas class within which the developer creates images such
as those used in a game.
Display Class
• The device’s screen is referred to as the display
• Each MIDlet has one and only one instance of the Display class
• The Displayable class has two subclasses-Screen class and the
Canvas class.
• The Screen class contains a subclass called the Item class, which
has its own subclasses used to display information or collect
information from a user (such as forms, check boxes, radio
buttons).
• The Screen class and its derived classes are referred to as high-
level user interface components.
• Displays created using the Canvas class are considered a low-
level user interface
• setCurrent() method is used to show the form.
• getCurrent() method of the is used to retrieve information
Command
The Command class constructor requires three parameters.
command label, the command type, command priority
cancel = new Command("Cancel", Command.CANCEL, 1);
• BACK Move to the previous screen
• CANCEL Cancel the current operation
• EXIT Terminate the application
• HELP Display help information
• ITEM Map the command to an item on the screen
• OK Positive acknowledgment
• SCREEN No direct key mapping available on device; command
will be mapped to object on a form or canvas
• STOP Stop the current operation
CommandListener
• The CommandListener is notified whenever the user
interacts with a command by way of the
commandAction() method.
public void commandAction(Command command,
Displayable displayable)
{
if (command == cancel)
{destroyApp(false);
notifyDestroyed();}}
helpMesg = new TextBox("Online Help", "Press
Back to return to the previous screen or press Exit
to close this,program.", 81, 0);
helpMesg.addCommand(back);
form.addCommand(exit);
form.addCommand(help);
form.setCommandListener(this);
helpMesg.setCommandListener(this);}
public void startApp(){display.setCurrent(form);}
public void pauseApp(){}
public void destroyApp(boolean unconditional){}
public void commandAction(Command command,
Displayable displayable)
{if (command == back){display.setCurrent(form);}
else if (command == exit){
destroyApp(false);
notifyDestroyed();}
else if (command == help)
{display.setCurrent(helpMesg);}}}
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class OnlineHelp extends MIDlet
implements CommandListener
{
private Display display;
private Command b ack;
private Command exit;
private Command help;
private Form form;
private TextBox helpMesg;
public OnlineHelp()
{
display = Display.getDisplay(this);
back = new Command("Back",
Command.BACK, 2);
exit = new Command("Exit",
Command.EXIT, 1);
help = new Command("Help",
Command.HELP, 3);
form = new Form("Online Help
Example");
Item class
• The Item class is derived from the Form class, and that gives an instance of
the Form class character and functionality by implementing text fields,
images, date fields, radio buttons, check boxes, and other features common
to most graphical user interfaces.
• A change in the status of an instance of the Item class is processed by the
itemStateChanged() method
Text Field
• The text field requires four values. These are title, text, maximum number
of characters that can be entered into the text field, and the TextField
constraint, which is zero to indicate there isn’t any constraint.
Item Listener
public void itemStateChanged(Item item)
{
if (item == selection)
{
StringItem msg = new StringItem("Your color is ",
radioButtons.getString(radioButtons.getSelectedIndex()));
form.append(msg);
}
• javax.microedition.lcdui.Display
• static Display getDisplay(MIDlet midlet)
• Displayable getCurrent()
• void setCurrent(Alert alert, Displayable displayable)
• void setCurrent (Displayable displayable)
• boolean isColor()
• int numColors()
Screen Class
• public class Display
• public abstract class Displayable
• public abstract class Screen extends Displayable
• public class Alert extends Screen
• public class Form extends Screen
• public class List extends Screen implements Choice
• public abstract class Item
• public class ChoiceGroup extends Item implements Choice
• public class DateField extends Item
• public class TextField extends Item
• public class Gauge extends Item
• public class ImageItem extends Item
• public class StringItem extends Item
• public class TextBox extends Screen
Screen Class
• public class Command
• public class Ticker
• public class Graphics
• public interface Choice
• public abstract class Canvas extends Displayable
• public class Graphics
Screen Class
• The TextBox class is used to display multi-line text on the
screen.
• The List class is used to display a list of items, as in a menu,
and enables the user to choose one of those items.
• The Alert class displays a dialog box containing a message
such as a warning.
• And the Form class is a container class that can display
multiple classes derived from the Item class.
Screen Class
• The Item class has six derived classes, any number of which
can be displayed within a Form object on the screen:
• ■ ChoiceGroup class used to display radio buttons and check
boxes
• ■ DateField class used for inputting a date into an application
• ■ TextField class used for inputting text into an application
• ■ Gauge class used to graphically show progress
• ■ ImageItem class used to display an image stored in a file
• ■ StringItem class used to display text on the screen
Alert Class
• An alert is a dialog box displayed by your program to warn a user of
a potential error such as a break in communication with a remote
computer.
• An alert can also be used to display any kind of message on the
screen, even if the message is not related to an error.
• alert = new Alert("Failure", "Lost communication link!", null, null);
• display.setCurrent(alert);
• Parameter includes title of the dialog box, text of the message
IMAGE displayed within the dialog box. And last isAlertType.
• ALARM Your request has been received.
• CONFIRMATION An event or processing is completed.
• ERROR An error is detected.
• INFO A nonerror alert occurred.
• WARNING A potential error could occur.
Alert Class
• An alert is a dialog box displayed by your program to warn a user of a
potential error such as a break in communication with a remote computer.
• An alert can also be used to display any kind of message on the screen,
even if the message is not related to an error.
• alert = new Alert("Failure", "Lost communication link!", null, null);
• display.setCurrent(alert);
• Parameter includes title of the dialog box, text of the message IMAGE
displayed within the dialog box. And last isAlertType.
• ALARM Your request has been received.
• CONFIRMATION An event or processing is completed.
• ERROR An error is detected.
• INFO A nonerror alert occurred.
• WARNING A potential error could occur.
• The setTimeout() method determines whether an alert dialog
box is a modal dialog box or a timed dialog box.
• The setTimeout() method has one parameter, which is the
default timeout value.
• Alert.FOREVER as the default timeout value for a modal alert
dialog box, or pass a time value in milliseconds indicating time
to terminate the alert dialog box.
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
Alert Class
Alert Sound
if (exitFlag == false)
{
AlertType.WARNING.playSound(display);
destroyApp(false);
}
Form Class
• An instance is placed with the instance of the Form class by
calling one of two methods.
• insert() method and append() method.
• The insert() method places the instance in a particular
position on the form as specified by parameters passed to the
insert() method.
• The append() method places the instance after the last object
on the form.
Item Class
• An Item class is a base class for a number of derived classes
that can be contained within a Form class.
• These derived classes are ChoiceGroup, DateField, Gauge,
ImageItem,StringItem, and TextField.
• The ChoiceGroup class is used to create check boxes or radio
buttons on a form, and the DateField class and TextField class
are used to capture date and free form text from the user of the
MIDlet.
ChoiceGroup Class
• J2ME classifies check boxes and radio buttons as the
ChoiceGroup class.
• An instance of the ChoiceGroup class can be one of two types:
exclusive or multiple.
• An exclusive instance appears as a set of radio buttons, and a
multiple instance contains one or a set of check boxes.
• EXCLUSIVE Only one selection available at any time
(radio button).
• MULTIPLE Zero or more selections available at any
time (check box).
• IMPLICIT Only one selection at any time. The
selection generates a command event
automatically. No icon is used (menu list).
DateField Class
• The DateField class is used to display, edit, or input date
and/or time into a MIDlet.
• A DateField class is instantiated by specifying a label for the
field, a field mode, and a time zone, although time zone is
optional.
• DateField datefield = new DateField("Today",
DateField.DATE);
• DateField datefield = new DateField("Time", DateField.TIME,
timeZone);
• DATE Display, edit, and input a date
• TIME Display, edit, and input a time
• DATE_TIME Display, edit, and input both date and time
Gauge Class
• The Gauge class creates an animated progress bar that
graphically represents the status of a process.
• The indicator on the gauge generated by the Gauge class
moves from one end to the other proportionally to the
completion of the process measured by the gauge.
• Gauge gauge = new Gauge("Like/Dislike Gauge", true, 100,
0);
• caption that is displayed with the gauge.
• a boolean value indicating whether or not the gauge is
interactive.
• maximum value of the gauge, and the last parameter is the
gauge’s initial value.
StringItem Class
• The purpose of using a StringItem class is to
display a text that cannot be modified or
deleted by the user of the MIDlet.
TextField
• The TextField class is used to capture one line or multiple lines
of text entered by the user.
• TextField class.textfield = new TextField("First Name:", "",
30, TextField.ANY);
• First is label ,The second parameter is text that you want to
appear as the default text. The third parameter is the maximum
number of characters that can be held by the instance
• CONSTRAINT_MASK Used to determine the
constraint’s current value
• ANY Input any character
• EMAILADDR Input only valid email address
• NUMERIC Input positive and negative numbers;
cannot exclude either positive or
negative numbers
• PASSWORD Hide input
• PHONENUMBER Input characters valid to a phone
number URL Input characters valid to a URL
Image Item
• Two types of images that can be displayed.
• These are immutable images and mutable images.
• An immutable image is loaded from a file or other resource
and cannot be modified once the image is displayed.
• Icons associated with MIDlets are immutable images.
• A mutable image is drawn on the screen using methods
available in the Graphics class. Once drawn, your MIDlet can
redraw any portion of the image.
• The createImage() method requires one parameter that
contains the name of the file containing the image.
• The next step is to create an instance of the ImageItem class. It
requires four parameters.
• The first is a string that becomes the label for the image. The
second parameter is reference to the instance of the Image
class created in step one.
• The third parameter is the layout directive. And the last
parameter is a string referred to as alternate text that is
displayed in place of the image if for some reason the image
cannot be displayed by the device.
• LAYOUT_DEFAULT Use the device’s default layout
• LAYOUT_LEFT Place image left
• LAYOUT_RIGHT Place image right
• LAYOUT_CENTER Center image
• LAYOUT_NEWLINE_BEFORE Start a new line and then
draw the image
• LAYOUT_NEWLINE_AFTER Draw the image and then start
a new line
List
• The List class is used to display a list of items on the screen
from which the user can select one or multiple items.
• There are three formats for the List class: radio buttons,
• check boxes, and an implicit list that does not use a radio
button or check box icon
• An instance is created without list items by passing the
constructor of the List class two parameters.
• The first parameter is a string that contains the titles of the list,
and the other parameter is the format of the list
Ticker Class
• The Ticker class is used to scroll text
horizontally on the screen much like a stock
ticker scrolls stock prices across the screen.
Low Level Display Canvas
• Each MIDlet has one instance of the Display class, and
the Display class has one derived class called the
Displayable class.
• MIDlet displays on the screen is created by an instance
of a class that is derived from the Displayable class.
• The Display class hierarchy is shown here:
public class Display
public abstract class Displayable
public abstract class Screen extends Displayable
public abstract class Canvas extends Displayable
public class Graphics
• The Displayable class has two subclasses: Screen and
Canvas.
• The Screen class and its derivatives are used
to create high-level components
• The Canvas class and its derivatives are used
to gain low-level access to the display, which is
necessary for graphic- and animation-based
applications.
• Agraphic is used with a canvas.
The Layout of a Canvas
• The canvas is divided into a virtual grid in which
each cell represents one pixel.Coordinates mark
the column and row of a cell within the grid
• The x coordinate represents the column, and the
y coordinate represents the cell’s row.
• The first cell located in the upper-left corner of
the grid has the coordinate location of 0, 0,where
the first zero is the x coordinate and the other
zero is the y coordinate.
• The canvas size of the device by calling the
• getWidth() and getHeight() methods of the
Canvas class.
• The coordinate of the center of the canvas is
calculated as:
• x = getWidth()/2
• y = getHeight()/2
• An image is drawn on a canvas using a virtual
pen. Using a virtual pen is very similar to
• using a real pen to draw an image on paper.
That is, the pen is dropped on the canvas
• at a specified coordinate, filling the cell with
the color of ink used in the pen.
• Graphical components used to create an image on a canvas
are drawn on the canvas when the paint() method of the
Displayable class is called. This is referred to as painting.
• The paint() method is an abstract method that is used both
by instances and derivatives of the Screen class and Canvas
class.
• The other method is paintContent(), which is called at the
end of the paint() method and contains statements to
actually draw the image.
protected void paint(Graphics graphics)
{
graphics.drawRect(12, 6, 40, 20));
}
• The paint() method is called automatically by the
setCurrent() method when the MIDlet is started.
• The repaint() whenever the canvas or a portion of the
canvas must be refreshed.
• repaint() method- One version requires no parameters
and repaints the entire canvas. The other version
requires four parameters that define the region of the
canvas that is to be repainted.
• The first two parameters are the x and y coordinates
for the upper-left corner of the region, and the last two
parameters are the width and height of the region.
• To specify a region of the canvas to repaint
whenever only a portion of the canvas has
changed and when you don’t want to waste time
repainting the entire canvas, such as when an
animated image is displayed on the screen. This is
known as clipping.
• Animation is the illusion of movement caused by
rapidly changing images on the screen, where
each image is slightly different from the previous
image. Each image displayed on the screen is
referred to as a frame.
• A key to successful animation is speed.
• A small portion of a frame changes in an animated
image. The repaint() method is capable of repainting
only the portion of the frame that changed rather than
the entire frame,which dramatically reduces the time
that is necessary to change a frame on the screen.
• The serviceRepaints() method directs the device’s
application manager to override outstanding requests
for service with the repaint request. The repaint
request becomes the next request to be processed by
the application manager.
• The device’s application manager calls the showNotify()
method immediately before the
• application manager displays the canvas.
• Define the showNotify() method with statements that
prepare the canvas for display, such as initializing resources
by beginning.
• The hideNotify() method is called by the application
manager after the canvas is emoved from the screen.
• Define the hideNotify() method with statements that free
• resources that were allocated when the showNotify()
method was called.
• This includes deactivating threads and resetting values
assigned to variables as necessary.
User Interactions
• The other technique is to use low-level user input
components that generate low-level user events.
• A key code is a numerical value sent by the small computing
device when the user of your application selects a particular
key. Each key on the device’s keypad is identified by a
unique key code.
• A game action is a keystroke that a person uses to play a
game on the small computing device. MIDP defines a set of
constants that represent keystrokes common to game
controllers.
• A pointer event is input received from a pointer device
attached to the small computing device, such as a touch
screen or mouse.
J2ME mobile device architecture a develo
• Three empty methods are called when a
particular key event occurs while your MIDlet
is running.
• . These methods are keyPressed(),
keyReleased(), and keyRepeated().
Working with Pointer Devices
• A person presses a pointer device by applying
pressure to a portion of a touch screen or by
clicking the mouse button. This causes a press
event. pointerPressed()
• A release event occurs once pressure is removed
from the touch screen or the mouse button.
pointerReleased()
• A drag event occurs whenever the person moves
the pointer device during a press event.
• pointerDragged()
Graphics
• Stroke Style and Color
• Every graphic context has two characteristics you
can control from within the MIDlet.-stroke style
and color.
• Stroke style defines the appearance of lines used
to draw an image on the canvas, and color
specifies the background and foreground color of
the image.
• Two kinds of stroke styles when drawing images
on the canvas: solid and dotted.
• The setStrokeStyle() method requires one
parameter, which is a constant that represents a
stroke style. There are two constants, SOLID and
DOTTED, both of which are members of the
Graphics class
• The current stroke style of a graphic context is
determined by calling the getStrokeStyle(). This
method returns an integer that can be compared
within your MIDlet to the stroke style constants.
• graphics.setFont(Font.getFont(Font.PROPORTIONAL,Font.BOLD |
Font.ITALIC, Font.SMALL);
• Font Constant Description Font Constant Value
• FACE_SYSTEM System font face 0
• FACE_MONOSPACE Monospace font face 32
• FACE_PROPORTIONAL Proportional font face 64
• STYLE_PLAIN Plain font style 0
• STYLE_BOLD Bold font style 1
• STYLE_ITALIC Italicized font style 2
• STYLE_UNDERLINED Underlined font style 4
• SIZE_SMALL Small font size 8
• SIZE_MEDIUM Medium font size 0
• SIZE_LARGE Large font size 16
• LEFT Coordinates represent the left edge of the
boundary box.
• HCENTER Coordinates represent the horizontal center
of the boundary box.
• RIGHT Coordinates represent the right edge of the
boundary box.
• TOP Coordinates represent the top edge of the
boundary box.
• BASELINE Coordinates represent the baseline for the
text.
• BOTTOM Coordinates represent the bottom edge of
the boundary box.
Images
• Anchor Point Constant
• LEFT Coordinates represent the left edge of the boundary
box.
• HCENTER Coordinates represent the horizontal center of
the boundary box.
• RIGHT Coordinates represent the right edge of the
boundary box.
• TOP Coordinates represent the top edge of the boundary
box.
• VCENTER Coordinates represent the baseline for the text.
• BOTTOM Coordinates represent the bottom edge of the
boundary box.
Record Enumeration
• A record store is more like a flat file than a database management
system and therefore lacks many sophisticated features that you
find in a database management system.
• For example, you cannot send an SQL query to a record store, nor
can you ask a record store to search for keywords or sort records,
which is commonly performed by a database management system.
• Still it can perform searches and sorts of records in a record store by
using the RecordEnumeration interface.
• An Enumeration provides a way to traverse data elements.
• The Enumeration object manages how data is retrieved from the
record store.
• Changes to the record store are reflected when the record store’s
content is iterated.
• Obtain a record enumeration by calling the
enumerateRecords() method.
• It requires three parameters. The first is the record
filter used to exclude records returned from the record
store.
• The second is reference to the record comparator,
which is a method used to compare records returned
from the record store.
• The last parameter is a boolean value indicating
whether or not the enumeration is automatically
updated when changes are made to the underlying
record store.
• There isn’t any filter or comparator method,
and the record enumeration is not
automatically updated when a change is made
to the record store.
• RecordEnumeration recordEnumeration
= recordstore.enumerateRecords(null,null,false);
• The hasNextElement() method is called to
evaluate whether or not there is another record
in the RecordEnumeration.
• A Boolean true is returned if another record
exists; otherwise, a Boolean false is returned.
• while ( recordEnumeration.hasNextElement())
{
//do something
}
• We can retrieve a record from the
RecordEnumeration using one of two
techniques.
• The first technique is designed to read a
record that has a single data type such as a
string
• The other technique reads a record that has a
compound data type.
• nextRecord() method, which returns a copy of
the next record in the RecordEnumeration.
• The record is passed to the constructor of the
String class and is assigned to the string
variable.
• String string = new
String(recordEnumeration.nextRecord());
• To move forward or back-nextRecord() and
previousRecord()
• Both the method return a byte array containing a copy of
the record.
• when the RecordEnumeration created it is positioned at
the top of the RecordEnumeration.
• The top is not the first record; you must call the
nextRecord() method to move to the first record.
• You can move to the last record by calling the
previousRecord()
• method while at the top of the RecordEnumeration.
• You can return to the top of the RecordEnumeration by
calling the reset() method.
• numRecords() method to determine the number of records
there are in the RecordEnumeration. The numRecords()
method returns an integer representing the total number
of records.
• If the return value is greater than zero, then evaluate
whether there is a next record or previous record
depending on the desired direction.
• The hasNextElement() method is called to determine
whether there is a next record.
• hasPreviousElement() method to determine whether there
is a previous record.
• Both methods return a boolean value indicating whether or
not there is another record.
• nextRecordId() determine the record ID of the next
record
• The keepUpdated() method has one parameter, which
is a boolean value indicating whether or not the
RecordEnumeration is automatically updated
• dated.
• To check the status of the automatic updating feature
call the isKeptUpdated() method.
• This method returns a boolean value indicating
whether or not the RecordEnumeration is
automatically updated.
• To rebuilt RecordEnumeration call the
rebuild() method.
• The rebuild() method should be called
whenever records in the underlying record
store change and the automatic update
feature is deactivated.
• Many times other MIDlets within the same
MIDlet suite can also change the record store
without notifying your MIDlet.
• In this case, you should create a
RecordListener, which notifies your MIDlet
• that the associated record store has changed
and that the MIDlet needs to call the
• rebuild() method.
Sorting Records
• Records within a RecordEnumeration are sorted by defining
a comparator class that is an implementation of the
RecordComparator interface.
• Within the comparator class you define a method that has
the logic to compare each record to determine whether the
record is equal to the current record or should precede or
follow the current record within the RecordEnumeration by
invoking compare(), requires two parameters, which are
two byte arrays that contain the current record and the
next record.
• These byte arrays are then converted to two strings that
are compared by using the compareTo() method of the
String class.
• The compareTo() method returns an integer that
is equal to zero, less than zero, or greater than
zero.
• A zero indicates that both strings are the same.
An integer less than zero indicates that the next
record precedes the current record in the
RecordEnumeration.
• An integer greater than zero indicates that the
next record follows the current record in the
RecordEnumeration.
• The compare() method returns a predefined comparison value.
• RecordComparator.EQUIVALENT,RecordComparator.PRECEDES,and
RecordComparator.FOLLOW
• The sort to appear in ascending order, then return the
RecordComparator.PRECEDES when the return value of the
compareTo() string is less than the current record and
RecordComparator.FOLLOW when the return value is greater than the
current record.
• For descending sort reverse these operations:
• EQUIVALENT Records passed to the compare() method are the
same.
• FOLLOW The record passed as the first parameter follows the
record passed as the second parameter.
• PRECEDES The record passed as the first parameter precedes the
record passed as the second parameter.
Searching
• Searching is referred to as filtering, where the filter is defined by the search criteria.
• Records that match the search criteria are copied into the RecordEnumeration.
• Those not matching the search criteria are filtered from the RecordEnumeration.
• The RecordFilter interface is used when searching for a record.
• Define two methods when defining an implementation of the RecordFilter
interface. -matches() method and the filterClose() method.
• The constructor accepts the search criteria as a parameter when your MIDlet
creates an instance of the implementation class.
• The matches() method contains the logic necessary to determine whether a
column fits the search criteria and returns a boolean value indicating whether or
not there is a match.
• The filterClose() method frees resources used by the implementation of the
RecordFilter interface once the search is completed.
• Logic contained in the matches() method reads one or multiple columns from the
current record and then applies logical operators to determine whether the record
meets the search criteria.
• Also sort the filtered records by first searching for a subset of records in the record
store, then sorting those records.
RecordListener
• Records in a RecordEnumeration might be a subset of records if filtering
has been applied
• Synchronize the RecordEnumeration and the record store by setting the
third parameter of the enumerateRecords() method to true.
• For example, you may want to change information on a form to reflect the
latest data in the record store.
• The instance of the RecordListener interface is notified whenever one of
three changes is made to the record store.
• These are when a record is added, modified, or deleted from the record
store.
• RecordListener interface must define three methods:
• recordAdded(), recordChanged(), and recordDeleted().
• All three methods require two parameters.
• The first parameter is reference to the record store that has changed,
• and the second is an integer indicating the record ID that was added,
modified, or removed from the record store.
recordstore.addRecordListener( new MyRecordListener());
class MyRecordListener implements RecordListener
{
public void recordAdded(RecordStore recordstore, int recordid)
{
try
{
//do something
}
catch (Exception error)
{
//do something
}}
public void recordDeleted(RecordStore recordstore, int recordid)
{
try
{
//do something
}
catch (Exception error)
{
//do something
}
}
public void recordChanged(RecordStore recordstore, int recordid)
{
try
{
//do something
}
catch (Exception error)
{
//do something
}
}
}

More Related Content

PDF
010118565.pdf
PPT
PPT
J2 me 1
PPTX
J2me Platform
PPTX
J2ME mobile app development
PPTX
Introduction to Mobile programming(J2ME)
PPT
J2ME-java-training-document-internal.ppt
010118565.pdf
J2 me 1
J2me Platform
J2ME mobile app development
Introduction to Mobile programming(J2ME)
J2ME-java-training-document-internal.ppt

Similar to J2ME mobile device architecture a develo (20)

PPTX
Introduction to mobile programing (J2ME)
PPTX
PPTX
Introduction To J2ME(FT - Prasanjit Dey)
PDF
Java 2 Micro Edition James White David Hemphill
PPT
Java ME CLDC MIDP
PPTX
PPTX
2 mobile development frameworks and tools dark temp
PPT
MOBILE APPs DEVELOPMENT PLATFORMS
PPTX
Java ME - 01 - Overview
PPTX
Java J2ME
PDF
J2me Crash Course
PPTX
PDF
J2me step by step
PPT
Mobile Application Development MAD J2ME UNIT 2
PPT
Mobile Application Development MAD J2ME
PDF
Java2 MicroEdition-J2ME
PPT
PPT
Scmad Chapter02
PPT
M app slides_1
PPT
Java ME An Introduction. www.javameblog.com
Introduction to mobile programing (J2ME)
Introduction To J2ME(FT - Prasanjit Dey)
Java 2 Micro Edition James White David Hemphill
Java ME CLDC MIDP
2 mobile development frameworks and tools dark temp
MOBILE APPs DEVELOPMENT PLATFORMS
Java ME - 01 - Overview
Java J2ME
J2me Crash Course
J2me step by step
Mobile Application Development MAD J2ME UNIT 2
Mobile Application Development MAD J2ME
Java2 MicroEdition-J2ME
Scmad Chapter02
M app slides_1
Java ME An Introduction. www.javameblog.com
Ad

Recently uploaded (20)

PPTX
OOP with Java - Java Introduction (Basics)
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PDF
Digital Logic Computer Design lecture notes
PPT
Project quality management in manufacturing
PPTX
Internet of Things (IOT) - A guide to understanding
DOCX
573137875-Attendance-Management-System-original
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PDF
Well-logging-methods_new................
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
bas. eng. economics group 4 presentation 1.pptx
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PDF
PPT on Performance Review to get promotions
PPTX
UNIT 4 Total Quality Management .pptx
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
Construction Project Organization Group 2.pptx
OOP with Java - Java Introduction (Basics)
Automation-in-Manufacturing-Chapter-Introduction.pdf
Digital Logic Computer Design lecture notes
Project quality management in manufacturing
Internet of Things (IOT) - A guide to understanding
573137875-Attendance-Management-System-original
R24 SURVEYING LAB MANUAL for civil enggi
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
Well-logging-methods_new................
CYBER-CRIMES AND SECURITY A guide to understanding
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
bas. eng. economics group 4 presentation 1.pptx
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPT on Performance Review to get promotions
UNIT 4 Total Quality Management .pptx
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
Model Code of Practice - Construction Work - 21102022 .pdf
Construction Project Organization Group 2.pptx
Ad

J2ME mobile device architecture a develo

  • 1. J2ME 1 Java 2 Platform, Micro Edition (J2ME)
  • 2. J2ME 2 Contents • What’s J2ME? • J2ME core concepts – Configurations (CLDC, CDC) – Profiles (MIDP) • MIDlet, MIDlet Suite • Basic classes API • Installation and using the Toolkit • Demos!!!
  • 3. J2ME 3 Introduction • Personalized and intelligent information appliances are necessities in our life today. • Such appliances can be: – cell phones – two-way pagers – smart cards – personal organizers – palmtops • These appliances tend to be special-purpose, limited- resource, network-connected devices.
  • 4. J2ME 4 Environment requirements • We need an environment which is adapted for constrained devices - devices that have limitations on what they can do when compared to standard desktop or server computers. • The constraints are: – extremely limited memory – small screen sizes – alternative input methods – slow processors
  • 5. J2ME 5 So – what’s the solution? • Because of the vast need, Sun has decided to develop a special edition of Java - J2ME (Java 2 Micro Edition).
  • 6. J2ME 6 Java Editions • Different devices have different requirements and different expectations of Java. • One platform (solution) cannot address all the market segments (web server, video games etc.) • Users/developers want flexibility. They want to choose what they want to use and what they do not.
  • 7. J2ME 7 Java Editions • The Java 2 Platform is split into three editions. • Each edition provides a complete environment for running Java-based applications, including the Java virtual machine (VM) and runtime classes. • The three editions target different kinds of applications running on different kinds of devices.
  • 8. J2ME 8 Java Editions Java2 Standard Edition (J2SE™) Java2 Enterprise Edition (J2EE™) Java2 Micro Edition (J2ME™) Java 2 Platform Standard desktop & workstation applications Heavy duty server systems Small & memory constrained devices
  • 9. J2ME 9 Java Editions • Each edition defines different sets of class libraries. • There are thousands of core J2SE runtime classes, taking up to 10-20 megabytes of space. • J2ME-based devices have fewer classes. J2ME J2SE J2EE
  • 10. J2ME 10 PersonalJava and EmbeddedJava • J2ME is not the first attempt at adapting Java for constrained environments. • PersonalJava – Uses the basic Java 1.1 runtime classes with a few features from Java 2. – Implementation still requires a couple of megabytes of memory and a fast processor to run.
  • 11. J2ME 11 PersonalJava and EmbeddedJava • EmbeddedJava – Makes every behavior of the JVM and the runtime classes optional - the implementor can choose exactly which classes and methods are required. – "write once, run anywhere".
  • 12. J2ME 12 J2ME Core Concepts • Configuration – Minimum platform required for a group of devices • Profile – Addresses specific needs of a certain device family • Optional Packages J2ME Profile/API J2ME Libraries Java Virtual Machine Host Operating System Java Language J2ME MIDP
  • 13. J2ME 13 J2ME Core Concepts J2ME is based on 3 core concepts: • Configurations • Profiles • Optional packages
  • 14. J2ME 14 Configurations • A configuration is a complete Java runtime environment, consisting of: – Java virtual machine (VM) to execute Java bytecode – Native code to interface to the underlying system – Set of core Java runtime classes • To use a configuration, a device must meet certain minimum requirements.
  • 15. J2ME 15 Configurations • The set of core classes is normally quite small and must be enhanced with additional classes supplied by J2ME profiles or by configuration implementor. • Configurations do not define any user interface classes.
  • 16. J2ME 16 Configurations Configuration CLDC CDC Connected Limited Device Configuration Connected Device Configuration
  • 17. J2ME 17 CLDC vs. CDC • CLDC – For very constrained devices – 160 - 512 KB of total memory – 16-bit or 32-bit processor – Low power consumption and often operating with battery power – Connectivity with limited bandwidth • CDC – 2 MB or more memory for Java platform – 32-bit processor – High bandwidth network connection, most often using TCP/IP
  • 18. J2ME 18 CLDC vs. CDC - VM • Features missing in the CLDC VM: – Floating point types – Object finalization – JNI or reflection – Thread groups or daemon threads – User Class loaders • Change in classfile verification  preverification • The CDC supports a complete, full- featured Java 2 virtual machine
  • 19. J2ME 19 J2ME Core Concepts J2ME is based on 3 core concepts: • Configurations • Profiles • Optional packages
  • 20. J2ME 20 Profiles • Adds domain-specific classes to a configuration: – To fill in missing functionality – To support specific uses of a device • Most profiles define user interface classes for building interactive applications. • To use a profile, the device must meet the minimum requirements of the underlying configuration and of the profile.
  • 21. J2ME 21 Profiles Profile MIDP PDAP PP PBP FP Mobile Information Device Profile Personal Digital Assistant Profile Foundation Profile Personal Basis Profile Personal Profile
  • 22. J2ME 22 MIDP – MID Profile • MIDP is targeted at a class of devices known as mobile information devices (MIDs). • Minimal characteristics of MIDs: – Enough memory to run MIDP applications – Display of at least 96 X 56 pixels, either monochrome or color – A keypad, keyboard, or touch screen – Two-way wireless networking capability
  • 23. J2ME 23 J2ME Core Concepts J2ME is based on 3 core concepts: • Configurations • Profiles • Optional packages
  • 24. J2ME 24 Optional Packages • Set of APIs in support of additional, common behaviors. • Have specific dependencies on a particular configuration and/or one or more profiles. • Examples of optional packages : – RMI Optional Package – Bluetooth Optional Package – JDBC Optional Package
  • 25. J2ME 25 What it all means • "J2ME application" is an ambiguous term. • Configuration, profile and optional packages should be chosen. • CDC-based profiles make development simpler due to J2SE-like APIs, but don’t suit the low-end devices. • CLDC-based profiles makes the development task harder, especially when trying to shrink the size of the application to run on many of the small devices.
  • 27. J2ME 27 MIDlets – The heart of J2ME… • MIDP does not support the running of applications that use a static main method as their entry point, nor calling the System.exit method in order to terminate. • Instead, we use a MIDlet, which is a MID Profile application.
  • 28. J2ME 28 MIDlets – The heart of J2ME… • Every application must extend javax.microedition.midlet.MIDlet class to allow the application management software to: – control the MIDlet – be able to retrieve properties from the application descriptor – notify and request state changes
  • 29. J2ME 29 MIDlets – The heart of J2ME… • The extending class is the main class of the application. • The MIDlet class defines abstract methods that the main class implements (for example: startApp(), destroyApp(), notifyDestroyed()).
  • 30. J2ME 30 MIDlet Suite • One or more MIDlets are packaged together into a MIDlet suite, composed of: – JAR (Java archive) file – JAD (Java Application Descriptor) file • All the user-defined classes and resources required by the suite's MIDlets must be in the JAR file.
  • 31. J2ME 31 MIDlet Suite • The JAR file must also include a manifest that describe the MIDlets in the suite. • The application descriptor (JAD) contains similar information, and is used by devices to obtain information about a MIDlet suite without having to download and install the MIDlet suite first.
  • 33. J2ME 33 Creating a MIDlet Importing MIDP specific packages import javax.microedition.lcdui.*; import javax.microedition.midlet.*;
  • 34. J2ME 34 Creating a MIDlet Extends MIDlet Implements CommandListener public class HelloMIDlet extends MIDlet implements CommandListener {
  • 35. J2ME 35 Creating a MIDlet Creating the form, adding the Commands public HelloMIDlet() { mMainForm = new Form("HelloMIDlet"); mMainForm.append(new StringItem(null, "Hello, Seminar Software Design!")); mMainForm.addCommand(new Command("Exit", Command.EXIT, 0)); mMainForm.setCommandListener(this); }
  • 36. J2ME 36 Sample MIDP classes API • MIDlet • Form • Command – CommandListener – ItemCommandListener • Item
  • 37. J2ME 37 Sample classes API • MIDlet – Base class • Form • Command – CommandListener – ItemCommandListener • Item
  • 38. J2ME 38 MIDlet class API • protected abstract void startApp() • protected abstract void pauseApp() • protected abstract void destroyApp(boolean unconditional) • public final String getAppProperty(String key) • public final void notifyDestroyed()
  • 39. J2ME 39 Sample classes API • MIDlet • Form • Command – CommandListener – ItemCommandListener • Item
  • 40. J2ME 40 Form class • A Form is a Screen that contains an arbitrary mixture of items: images, read-only text fields, editable text fields, editable date fields, gauges, choice groups, and custom items. • In general, any subclass of the Item class may be contained within a form. • The implementation handles layout, traversal, and scrolling.
  • 41. J2ME 41 Form class API • Item management –public int append(Item item) –public Item get(int itemNum) • Layout • public void setItemStateListener(ItemStateL istener iListener)
  • 42. J2ME 42 Sample classes API • MIDlet • Form • Command – CommandListener – ItemCommadListener • Item
  • 43. J2ME 43 Command class • The Command class represents the semantic meaning of an action. Command objects are presented in the user interface. • The action itself is implemented in a CommandListener object. • The CommandListener is associated with a Displayable or an Item. • Once the Command is called – the CommandListener is invoked, and the action is performed.
  • 44. J2ME 44 Command class • Command label –public String getLabel() • Command type –public int getCommandType() • Command priority –public int getPriority()
  • 45. J2ME 45 CommandListener class API • This object is a listener for Commands that are attached to a Displayable. • public void commandAction(Command c, Displayable d)
  • 46. J2ME 46 ItemCommandListener class API • When a command (attached to an Item) is invoked, the application is notified by having the commandAction() method called on the ItemCommandListener that had been set on the Item. • public void commandAction(Command c, Item item)
  • 47. J2ME 47 Sample classes API • MIDlet • Form • Command – CommandListener – ItemCommandListener • Item
  • 48. J2ME 48 Item class • A superclass for components that can be added to a Form. • All Item objects have a label field • Choose the Item’s layout, size, and appearance • Attach Commands
  • 49. J2ME 49 Item class API • public void setDefaultCommand(Command cmd) • public void setItemCommandListener(ItemComm andListener listener) • public void notifyStateChanged() • public int getPreferredWidth()
  • 50. J2ME 50 Getting Started… –1st step: Download sun’s J2ME Wireless Toolkit from: http://java.sun.com/products/j2mewtoolkit/do wnload-2_1.html –2nd step: Make sure you have J2SE SDK installed –3rd step: Install the J2ME Toolkit.
  • 52. User Interface • A user interface is a set of routines that displays information on the screen, prompts the user to perform a task, and then processes the task. • For example, a J2ME email application might display a list of menu options, such as Inbox, Compose, and Exit, and then prompt the user to make a selection by moving the cursor keys and pressing a key on the small computing device. • The device’s application manager passes the selection to the application, where it is compared with known options.
  • 53. User Interface (contd) • Three kinds of user interfaces command, form, or canvas • A command-based user interface consists of instances of the Command class. For example, Exit ,Help • A form-based user interface consists of an instance of the Form class that contains instances derived from the Item class such as text boxes, radio buttons, check boxes, lists etc to display information on the screen and to collect input from the user. • A canvas-based user interface consists of instances of the Canvas class within which the developer creates images such as those used in a game.
  • 54. Display Class • The device’s screen is referred to as the display • Each MIDlet has one and only one instance of the Display class • The Displayable class has two subclasses-Screen class and the Canvas class. • The Screen class contains a subclass called the Item class, which has its own subclasses used to display information or collect information from a user (such as forms, check boxes, radio buttons). • The Screen class and its derived classes are referred to as high- level user interface components. • Displays created using the Canvas class are considered a low- level user interface • setCurrent() method is used to show the form. • getCurrent() method of the is used to retrieve information
  • 55. Command The Command class constructor requires three parameters. command label, the command type, command priority cancel = new Command("Cancel", Command.CANCEL, 1); • BACK Move to the previous screen • CANCEL Cancel the current operation • EXIT Terminate the application • HELP Display help information • ITEM Map the command to an item on the screen • OK Positive acknowledgment • SCREEN No direct key mapping available on device; command will be mapped to object on a form or canvas • STOP Stop the current operation
  • 56. CommandListener • The CommandListener is notified whenever the user interacts with a command by way of the commandAction() method. public void commandAction(Command command, Displayable displayable) { if (command == cancel) {destroyApp(false); notifyDestroyed();}}
  • 57. helpMesg = new TextBox("Online Help", "Press Back to return to the previous screen or press Exit to close this,program.", 81, 0); helpMesg.addCommand(back); form.addCommand(exit); form.addCommand(help); form.setCommandListener(this); helpMesg.setCommandListener(this);} public void startApp(){display.setCurrent(form);} public void pauseApp(){} public void destroyApp(boolean unconditional){} public void commandAction(Command command, Displayable displayable) {if (command == back){display.setCurrent(form);} else if (command == exit){ destroyApp(false); notifyDestroyed();} else if (command == help) {display.setCurrent(helpMesg);}}} import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class OnlineHelp extends MIDlet implements CommandListener { private Display display; private Command b ack; private Command exit; private Command help; private Form form; private TextBox helpMesg; public OnlineHelp() { display = Display.getDisplay(this); back = new Command("Back", Command.BACK, 2); exit = new Command("Exit", Command.EXIT, 1); help = new Command("Help", Command.HELP, 3); form = new Form("Online Help Example");
  • 58. Item class • The Item class is derived from the Form class, and that gives an instance of the Form class character and functionality by implementing text fields, images, date fields, radio buttons, check boxes, and other features common to most graphical user interfaces. • A change in the status of an instance of the Item class is processed by the itemStateChanged() method Text Field • The text field requires four values. These are title, text, maximum number of characters that can be entered into the text field, and the TextField constraint, which is zero to indicate there isn’t any constraint.
  • 59. Item Listener public void itemStateChanged(Item item) { if (item == selection) { StringItem msg = new StringItem("Your color is ", radioButtons.getString(radioButtons.getSelectedIndex())); form.append(msg); }
  • 60. • javax.microedition.lcdui.Display • static Display getDisplay(MIDlet midlet) • Displayable getCurrent() • void setCurrent(Alert alert, Displayable displayable) • void setCurrent (Displayable displayable) • boolean isColor() • int numColors()
  • 61. Screen Class • public class Display • public abstract class Displayable • public abstract class Screen extends Displayable • public class Alert extends Screen • public class Form extends Screen • public class List extends Screen implements Choice • public abstract class Item • public class ChoiceGroup extends Item implements Choice • public class DateField extends Item • public class TextField extends Item • public class Gauge extends Item • public class ImageItem extends Item • public class StringItem extends Item • public class TextBox extends Screen
  • 62. Screen Class • public class Command • public class Ticker • public class Graphics • public interface Choice • public abstract class Canvas extends Displayable • public class Graphics
  • 63. Screen Class • The TextBox class is used to display multi-line text on the screen. • The List class is used to display a list of items, as in a menu, and enables the user to choose one of those items. • The Alert class displays a dialog box containing a message such as a warning. • And the Form class is a container class that can display multiple classes derived from the Item class.
  • 64. Screen Class • The Item class has six derived classes, any number of which can be displayed within a Form object on the screen: • ■ ChoiceGroup class used to display radio buttons and check boxes • ■ DateField class used for inputting a date into an application • ■ TextField class used for inputting text into an application • ■ Gauge class used to graphically show progress • ■ ImageItem class used to display an image stored in a file • ■ StringItem class used to display text on the screen
  • 65. Alert Class • An alert is a dialog box displayed by your program to warn a user of a potential error such as a break in communication with a remote computer. • An alert can also be used to display any kind of message on the screen, even if the message is not related to an error. • alert = new Alert("Failure", "Lost communication link!", null, null); • display.setCurrent(alert); • Parameter includes title of the dialog box, text of the message IMAGE displayed within the dialog box. And last isAlertType. • ALARM Your request has been received. • CONFIRMATION An event or processing is completed. • ERROR An error is detected. • INFO A nonerror alert occurred. • WARNING A potential error could occur.
  • 66. Alert Class • An alert is a dialog box displayed by your program to warn a user of a potential error such as a break in communication with a remote computer. • An alert can also be used to display any kind of message on the screen, even if the message is not related to an error. • alert = new Alert("Failure", "Lost communication link!", null, null); • display.setCurrent(alert); • Parameter includes title of the dialog box, text of the message IMAGE displayed within the dialog box. And last isAlertType. • ALARM Your request has been received. • CONFIRMATION An event or processing is completed. • ERROR An error is detected. • INFO A nonerror alert occurred. • WARNING A potential error could occur.
  • 67. • The setTimeout() method determines whether an alert dialog box is a modal dialog box or a timed dialog box. • The setTimeout() method has one parameter, which is the default timeout value. • Alert.FOREVER as the default timeout value for a modal alert dialog box, or pass a time value in milliseconds indicating time to terminate the alert dialog box. alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); Alert Class
  • 68. Alert Sound if (exitFlag == false) { AlertType.WARNING.playSound(display); destroyApp(false); }
  • 69. Form Class • An instance is placed with the instance of the Form class by calling one of two methods. • insert() method and append() method. • The insert() method places the instance in a particular position on the form as specified by parameters passed to the insert() method. • The append() method places the instance after the last object on the form.
  • 70. Item Class • An Item class is a base class for a number of derived classes that can be contained within a Form class. • These derived classes are ChoiceGroup, DateField, Gauge, ImageItem,StringItem, and TextField. • The ChoiceGroup class is used to create check boxes or radio buttons on a form, and the DateField class and TextField class are used to capture date and free form text from the user of the MIDlet.
  • 71. ChoiceGroup Class • J2ME classifies check boxes and radio buttons as the ChoiceGroup class. • An instance of the ChoiceGroup class can be one of two types: exclusive or multiple. • An exclusive instance appears as a set of radio buttons, and a multiple instance contains one or a set of check boxes. • EXCLUSIVE Only one selection available at any time (radio button). • MULTIPLE Zero or more selections available at any time (check box). • IMPLICIT Only one selection at any time. The selection generates a command event automatically. No icon is used (menu list).
  • 72. DateField Class • The DateField class is used to display, edit, or input date and/or time into a MIDlet. • A DateField class is instantiated by specifying a label for the field, a field mode, and a time zone, although time zone is optional. • DateField datefield = new DateField("Today", DateField.DATE); • DateField datefield = new DateField("Time", DateField.TIME, timeZone); • DATE Display, edit, and input a date • TIME Display, edit, and input a time • DATE_TIME Display, edit, and input both date and time
  • 73. Gauge Class • The Gauge class creates an animated progress bar that graphically represents the status of a process. • The indicator on the gauge generated by the Gauge class moves from one end to the other proportionally to the completion of the process measured by the gauge. • Gauge gauge = new Gauge("Like/Dislike Gauge", true, 100, 0); • caption that is displayed with the gauge. • a boolean value indicating whether or not the gauge is interactive. • maximum value of the gauge, and the last parameter is the gauge’s initial value.
  • 74. StringItem Class • The purpose of using a StringItem class is to display a text that cannot be modified or deleted by the user of the MIDlet.
  • 75. TextField • The TextField class is used to capture one line or multiple lines of text entered by the user. • TextField class.textfield = new TextField("First Name:", "", 30, TextField.ANY); • First is label ,The second parameter is text that you want to appear as the default text. The third parameter is the maximum number of characters that can be held by the instance
  • 76. • CONSTRAINT_MASK Used to determine the constraint’s current value • ANY Input any character • EMAILADDR Input only valid email address • NUMERIC Input positive and negative numbers; cannot exclude either positive or negative numbers • PASSWORD Hide input • PHONENUMBER Input characters valid to a phone number URL Input characters valid to a URL
  • 77. Image Item • Two types of images that can be displayed. • These are immutable images and mutable images. • An immutable image is loaded from a file or other resource and cannot be modified once the image is displayed. • Icons associated with MIDlets are immutable images. • A mutable image is drawn on the screen using methods available in the Graphics class. Once drawn, your MIDlet can redraw any portion of the image.
  • 78. • The createImage() method requires one parameter that contains the name of the file containing the image. • The next step is to create an instance of the ImageItem class. It requires four parameters. • The first is a string that becomes the label for the image. The second parameter is reference to the instance of the Image class created in step one. • The third parameter is the layout directive. And the last parameter is a string referred to as alternate text that is displayed in place of the image if for some reason the image cannot be displayed by the device.
  • 79. • LAYOUT_DEFAULT Use the device’s default layout • LAYOUT_LEFT Place image left • LAYOUT_RIGHT Place image right • LAYOUT_CENTER Center image • LAYOUT_NEWLINE_BEFORE Start a new line and then draw the image • LAYOUT_NEWLINE_AFTER Draw the image and then start a new line
  • 80. List • The List class is used to display a list of items on the screen from which the user can select one or multiple items. • There are three formats for the List class: radio buttons, • check boxes, and an implicit list that does not use a radio button or check box icon • An instance is created without list items by passing the constructor of the List class two parameters. • The first parameter is a string that contains the titles of the list, and the other parameter is the format of the list
  • 81. Ticker Class • The Ticker class is used to scroll text horizontally on the screen much like a stock ticker scrolls stock prices across the screen.
  • 83. • Each MIDlet has one instance of the Display class, and the Display class has one derived class called the Displayable class. • MIDlet displays on the screen is created by an instance of a class that is derived from the Displayable class. • The Display class hierarchy is shown here: public class Display public abstract class Displayable public abstract class Screen extends Displayable public abstract class Canvas extends Displayable public class Graphics • The Displayable class has two subclasses: Screen and Canvas.
  • 84. • The Screen class and its derivatives are used to create high-level components • The Canvas class and its derivatives are used to gain low-level access to the display, which is necessary for graphic- and animation-based applications. • Agraphic is used with a canvas.
  • 85. The Layout of a Canvas • The canvas is divided into a virtual grid in which each cell represents one pixel.Coordinates mark the column and row of a cell within the grid • The x coordinate represents the column, and the y coordinate represents the cell’s row. • The first cell located in the upper-left corner of the grid has the coordinate location of 0, 0,where the first zero is the x coordinate and the other zero is the y coordinate.
  • 86. • The canvas size of the device by calling the • getWidth() and getHeight() methods of the Canvas class. • The coordinate of the center of the canvas is calculated as: • x = getWidth()/2 • y = getHeight()/2
  • 87. • An image is drawn on a canvas using a virtual pen. Using a virtual pen is very similar to • using a real pen to draw an image on paper. That is, the pen is dropped on the canvas • at a specified coordinate, filling the cell with the color of ink used in the pen.
  • 88. • Graphical components used to create an image on a canvas are drawn on the canvas when the paint() method of the Displayable class is called. This is referred to as painting. • The paint() method is an abstract method that is used both by instances and derivatives of the Screen class and Canvas class. • The other method is paintContent(), which is called at the end of the paint() method and contains statements to actually draw the image. protected void paint(Graphics graphics) { graphics.drawRect(12, 6, 40, 20)); }
  • 89. • The paint() method is called automatically by the setCurrent() method when the MIDlet is started. • The repaint() whenever the canvas or a portion of the canvas must be refreshed. • repaint() method- One version requires no parameters and repaints the entire canvas. The other version requires four parameters that define the region of the canvas that is to be repainted. • The first two parameters are the x and y coordinates for the upper-left corner of the region, and the last two parameters are the width and height of the region.
  • 90. • To specify a region of the canvas to repaint whenever only a portion of the canvas has changed and when you don’t want to waste time repainting the entire canvas, such as when an animated image is displayed on the screen. This is known as clipping. • Animation is the illusion of movement caused by rapidly changing images on the screen, where each image is slightly different from the previous image. Each image displayed on the screen is referred to as a frame.
  • 91. • A key to successful animation is speed. • A small portion of a frame changes in an animated image. The repaint() method is capable of repainting only the portion of the frame that changed rather than the entire frame,which dramatically reduces the time that is necessary to change a frame on the screen. • The serviceRepaints() method directs the device’s application manager to override outstanding requests for service with the repaint request. The repaint request becomes the next request to be processed by the application manager.
  • 92. • The device’s application manager calls the showNotify() method immediately before the • application manager displays the canvas. • Define the showNotify() method with statements that prepare the canvas for display, such as initializing resources by beginning. • The hideNotify() method is called by the application manager after the canvas is emoved from the screen. • Define the hideNotify() method with statements that free • resources that were allocated when the showNotify() method was called. • This includes deactivating threads and resetting values assigned to variables as necessary.
  • 93. User Interactions • The other technique is to use low-level user input components that generate low-level user events. • A key code is a numerical value sent by the small computing device when the user of your application selects a particular key. Each key on the device’s keypad is identified by a unique key code. • A game action is a keystroke that a person uses to play a game on the small computing device. MIDP defines a set of constants that represent keystrokes common to game controllers. • A pointer event is input received from a pointer device attached to the small computing device, such as a touch screen or mouse.
  • 95. • Three empty methods are called when a particular key event occurs while your MIDlet is running. • . These methods are keyPressed(), keyReleased(), and keyRepeated().
  • 96. Working with Pointer Devices • A person presses a pointer device by applying pressure to a portion of a touch screen or by clicking the mouse button. This causes a press event. pointerPressed() • A release event occurs once pressure is removed from the touch screen or the mouse button. pointerReleased() • A drag event occurs whenever the person moves the pointer device during a press event. • pointerDragged()
  • 97. Graphics • Stroke Style and Color • Every graphic context has two characteristics you can control from within the MIDlet.-stroke style and color. • Stroke style defines the appearance of lines used to draw an image on the canvas, and color specifies the background and foreground color of the image. • Two kinds of stroke styles when drawing images on the canvas: solid and dotted.
  • 98. • The setStrokeStyle() method requires one parameter, which is a constant that represents a stroke style. There are two constants, SOLID and DOTTED, both of which are members of the Graphics class • The current stroke style of a graphic context is determined by calling the getStrokeStyle(). This method returns an integer that can be compared within your MIDlet to the stroke style constants.
  • 99. • graphics.setFont(Font.getFont(Font.PROPORTIONAL,Font.BOLD | Font.ITALIC, Font.SMALL); • Font Constant Description Font Constant Value • FACE_SYSTEM System font face 0 • FACE_MONOSPACE Monospace font face 32 • FACE_PROPORTIONAL Proportional font face 64 • STYLE_PLAIN Plain font style 0 • STYLE_BOLD Bold font style 1 • STYLE_ITALIC Italicized font style 2 • STYLE_UNDERLINED Underlined font style 4 • SIZE_SMALL Small font size 8 • SIZE_MEDIUM Medium font size 0 • SIZE_LARGE Large font size 16
  • 100. • LEFT Coordinates represent the left edge of the boundary box. • HCENTER Coordinates represent the horizontal center of the boundary box. • RIGHT Coordinates represent the right edge of the boundary box. • TOP Coordinates represent the top edge of the boundary box. • BASELINE Coordinates represent the baseline for the text. • BOTTOM Coordinates represent the bottom edge of the boundary box.
  • 101. Images • Anchor Point Constant • LEFT Coordinates represent the left edge of the boundary box. • HCENTER Coordinates represent the horizontal center of the boundary box. • RIGHT Coordinates represent the right edge of the boundary box. • TOP Coordinates represent the top edge of the boundary box. • VCENTER Coordinates represent the baseline for the text. • BOTTOM Coordinates represent the bottom edge of the boundary box.
  • 103. • A record store is more like a flat file than a database management system and therefore lacks many sophisticated features that you find in a database management system. • For example, you cannot send an SQL query to a record store, nor can you ask a record store to search for keywords or sort records, which is commonly performed by a database management system. • Still it can perform searches and sorts of records in a record store by using the RecordEnumeration interface. • An Enumeration provides a way to traverse data elements. • The Enumeration object manages how data is retrieved from the record store. • Changes to the record store are reflected when the record store’s content is iterated.
  • 104. • Obtain a record enumeration by calling the enumerateRecords() method. • It requires three parameters. The first is the record filter used to exclude records returned from the record store. • The second is reference to the record comparator, which is a method used to compare records returned from the record store. • The last parameter is a boolean value indicating whether or not the enumeration is automatically updated when changes are made to the underlying record store.
  • 105. • There isn’t any filter or comparator method, and the record enumeration is not automatically updated when a change is made to the record store. • RecordEnumeration recordEnumeration = recordstore.enumerateRecords(null,null,false);
  • 106. • The hasNextElement() method is called to evaluate whether or not there is another record in the RecordEnumeration. • A Boolean true is returned if another record exists; otherwise, a Boolean false is returned. • while ( recordEnumeration.hasNextElement()) { //do something }
  • 107. • We can retrieve a record from the RecordEnumeration using one of two techniques. • The first technique is designed to read a record that has a single data type such as a string • The other technique reads a record that has a compound data type.
  • 108. • nextRecord() method, which returns a copy of the next record in the RecordEnumeration. • The record is passed to the constructor of the String class and is assigned to the string variable. • String string = new String(recordEnumeration.nextRecord());
  • 109. • To move forward or back-nextRecord() and previousRecord() • Both the method return a byte array containing a copy of the record. • when the RecordEnumeration created it is positioned at the top of the RecordEnumeration. • The top is not the first record; you must call the nextRecord() method to move to the first record. • You can move to the last record by calling the previousRecord() • method while at the top of the RecordEnumeration. • You can return to the top of the RecordEnumeration by calling the reset() method.
  • 110. • numRecords() method to determine the number of records there are in the RecordEnumeration. The numRecords() method returns an integer representing the total number of records. • If the return value is greater than zero, then evaluate whether there is a next record or previous record depending on the desired direction. • The hasNextElement() method is called to determine whether there is a next record. • hasPreviousElement() method to determine whether there is a previous record. • Both methods return a boolean value indicating whether or not there is another record.
  • 111. • nextRecordId() determine the record ID of the next record • The keepUpdated() method has one parameter, which is a boolean value indicating whether or not the RecordEnumeration is automatically updated • dated. • To check the status of the automatic updating feature call the isKeptUpdated() method. • This method returns a boolean value indicating whether or not the RecordEnumeration is automatically updated.
  • 112. • To rebuilt RecordEnumeration call the rebuild() method. • The rebuild() method should be called whenever records in the underlying record store change and the automatic update feature is deactivated.
  • 113. • Many times other MIDlets within the same MIDlet suite can also change the record store without notifying your MIDlet. • In this case, you should create a RecordListener, which notifies your MIDlet • that the associated record store has changed and that the MIDlet needs to call the • rebuild() method.
  • 114. Sorting Records • Records within a RecordEnumeration are sorted by defining a comparator class that is an implementation of the RecordComparator interface. • Within the comparator class you define a method that has the logic to compare each record to determine whether the record is equal to the current record or should precede or follow the current record within the RecordEnumeration by invoking compare(), requires two parameters, which are two byte arrays that contain the current record and the next record. • These byte arrays are then converted to two strings that are compared by using the compareTo() method of the String class.
  • 115. • The compareTo() method returns an integer that is equal to zero, less than zero, or greater than zero. • A zero indicates that both strings are the same. An integer less than zero indicates that the next record precedes the current record in the RecordEnumeration. • An integer greater than zero indicates that the next record follows the current record in the RecordEnumeration.
  • 116. • The compare() method returns a predefined comparison value. • RecordComparator.EQUIVALENT,RecordComparator.PRECEDES,and RecordComparator.FOLLOW • The sort to appear in ascending order, then return the RecordComparator.PRECEDES when the return value of the compareTo() string is less than the current record and RecordComparator.FOLLOW when the return value is greater than the current record. • For descending sort reverse these operations: • EQUIVALENT Records passed to the compare() method are the same. • FOLLOW The record passed as the first parameter follows the record passed as the second parameter. • PRECEDES The record passed as the first parameter precedes the record passed as the second parameter.
  • 117. Searching • Searching is referred to as filtering, where the filter is defined by the search criteria. • Records that match the search criteria are copied into the RecordEnumeration. • Those not matching the search criteria are filtered from the RecordEnumeration. • The RecordFilter interface is used when searching for a record. • Define two methods when defining an implementation of the RecordFilter interface. -matches() method and the filterClose() method. • The constructor accepts the search criteria as a parameter when your MIDlet creates an instance of the implementation class. • The matches() method contains the logic necessary to determine whether a column fits the search criteria and returns a boolean value indicating whether or not there is a match. • The filterClose() method frees resources used by the implementation of the RecordFilter interface once the search is completed. • Logic contained in the matches() method reads one or multiple columns from the current record and then applies logical operators to determine whether the record meets the search criteria. • Also sort the filtered records by first searching for a subset of records in the record store, then sorting those records.
  • 118. RecordListener • Records in a RecordEnumeration might be a subset of records if filtering has been applied • Synchronize the RecordEnumeration and the record store by setting the third parameter of the enumerateRecords() method to true. • For example, you may want to change information on a form to reflect the latest data in the record store. • The instance of the RecordListener interface is notified whenever one of three changes is made to the record store. • These are when a record is added, modified, or deleted from the record store. • RecordListener interface must define three methods: • recordAdded(), recordChanged(), and recordDeleted(). • All three methods require two parameters. • The first parameter is reference to the record store that has changed, • and the second is an integer indicating the record ID that was added, modified, or removed from the record store.
  • 119. recordstore.addRecordListener( new MyRecordListener()); class MyRecordListener implements RecordListener { public void recordAdded(RecordStore recordstore, int recordid) { try { //do something } catch (Exception error) { //do something }}
  • 120. public void recordDeleted(RecordStore recordstore, int recordid) { try { //do something } catch (Exception error) { //do something } } public void recordChanged(RecordStore recordstore, int recordid) { try { //do something } catch (Exception error) { //do something } } }