The J2ME Big Index
Transcript of The J2ME Big Index
-
8/14/2019 The J2ME Big Index
1/97
he J2ME Big Index
e J2MEpersonal
torial
The Big IndexA list of all content pages in the The J2MEpersonalTutorial
q
q
Part 1: Creating MIDlets
J2ME Introduction
Acquiring and Installing the J2ME Development Kit
Understanding the Process of MIDlet Creation--Without the Toolkit
Step 1: Design
Step 2: Code
Step 3: Compile
Step 4: Preverify
Step 5: Package
Step 6: Test
Step 7: Deploy
Understanding the Process of MIDlet Creation--Using the Toolkit
The MIDlet Lifecycle
Part 2: User Interfaces with MIDP 2.0
User Interface Architecture Alert
List
TextBox
Form
Images, Tickers, and Gauges
Handling User CommandsWorking with the Low-Level API
Part 3: Exploring the Game API of MIDP 2.0
J2ME Gaming API: An Overview
A Very Short Primer on Game Building
Building a J2ME Game: Start with the GameCanvas
Defining Game Characteristics
Building a J2ME Game: Creating Backgrounds Using the TiledLayer class
le:///C|/Documents%20and%20Settings/akanksha/reallybigindex.html (1 of 2)7/14/2006 12:38:54 PM
http://c%7C/Documents%20and%20Settings/akanksha/index.htmlhttp://c%7C/Documents%20and%20Settings/akanksha/index.htmlhttp://c%7C/Documents%20and%20Settings/akanksha/index.htmlhttp://c%7C/Documents%20and%20Settings/akanksha/index.htmlhttp://c%7C/Documents%20and%20Settings/akanksha/index.htmlhttp://c%7C/Documents%20and%20Settings/akanksha/index.html -
8/14/2019 The J2ME Big Index
2/97
-
8/14/2019 The J2ME Big Index
3/97
ava.net: J2ME Tutorial, Part 1: Creating MIDlets
J2ME Tutorial, Part 1: Creating MIDletsby Vikram Goyal
02/09/2005
va 2 Micro Edition (J2ME) combines a resource-constrained JVM and a set of Java APIs for developingplications for mobile devices. This article is the first in a series. This time, after a quick introduction to J2
will provide a step-by-step guide to creating J2ME applications, also known as MIDlets, using a simpleample. This will cover how to test and deploy these MIDlets as well. Finally, I will round out this installmeth a look at the lifecycle of a MIDlet.
2ME Introduction
hat is J2ME? Cut away the hype and the excess fat and you are left with yet another (set of) Java APIs.nce these APIs cannot run on a traditional Java Virtual Machine (JVM), due to the limited size of mobilevices in regards to memory and resource availability, J2ME defines a limited version of the JVM as well.tshell:
2ME combines a resource constrained JVM and a set of Java APIs for developing applications for mobileevices.
o you, as a developer, have to install this JVM and the APIs on mobile devices? No. Device manufacturerstall and prepackage their devices with this JVM (and associated APIs). As a developer, you only need tovelop applications targeting these devices and install them. Easier said than done!
ME can be divided into three parts, as shown in Figure 1: a configuration, a profile, and optional packagenfiguration contains the JVM (not the traditional JVM, but the cut-down version) and some class librariesofile builds on top of these base class libraries by providing a useful set of APIs; and optional packages, ell, an optional set of APIs that you may or may not use when creating your applications. Optional package traditionally not packaged by the device manufacturers, and you have to package and distribute them w
ur application. The configuration and profile are supplied by the device manufacturers and they embeddeem in the devices.
le:///C|/Documents%20and%20Settings/akanksha/j2me/j2me11.htm (1 of 3)7/14/2006 12:38:56 PM
http://today.java.net/pub/au/179http://today.java.net/pub/au/179http://www.java.net/ -
8/14/2019 The J2ME Big Index
4/97
ava.net: J2ME Tutorial, Part 1: Creating MIDlets
gure 1. The J2ME stack
e most popular profile and configuration that Sun provides are the Mobile Information Device Profile (MIDd Connected Limited Device Configuration (CLDC), respectively. As the name suggests, CLDC is forvices with limited configurations; for example, devices that have only 128 to 512KB of memory available va applications. Consequently, the JVM that it provides is very limited and supports only a small number
aditional Java classes. (This limited JVM is actually called the KVM.) Its counterpart, the Connected Devic
onfiguration (CDC) is for devices with at least 2MB of memory available and supports a more feature-richVM (but still not a standard JVM).
e MID profile complements the CLDC configuration very well because it minimizes both the memory andwer required for limited devices. It provides the basic API that is used for creating application for thesevices. For example, it provides the javax.microedition.lcdui package that allows us to create the
UI elements that can be shown on a (limited) device running the MID profile on top of a CLDC configuratioote that MIDP cannot be used with CDC devices. CDC devices get their own set of profiles, like theoundation and Personal profiles. However, I will not cover these profiles or the CDC here, and willncentrate on using MIDP and CLDC only.
e latest versions of MIDP and CLDC are 2.0 and 1.1, respectively. Not many devices currently support trsions, but the list is growing rapidly. Sun maintains a list of devices according to version.
cquiring and Installing the J2ME Development Kit
etting started with developing applications (henceforth called "MIDlets") for the J2ME platform is easy.though device manufacturers install and prepackage their devices with this JVM (and associated APIs), yll need to install the J2ME Wireless Toolkit 2.2 on your development machine. Before that, however, you
le:///C|/Documents%20and%20Settings/akanksha/j2me/j2me11.htm (2 of 3)7/14/2006 12:38:56 PM
http://developers.sun.com/techtopics/mobility/device/http://java.sun.com/products/j2mewtoolkit/download-2_2.htmlhttp://java.sun.com/products/j2mewtoolkit/download-2_2.htmlhttp://developers.sun.com/techtopics/mobility/device/ -
8/14/2019 The J2ME Big Index
5/97
ava.net: J2ME Tutorial, Part 1: Creating MIDlets
ust also have the Java Development Kit (JDK), version 1.4.2 or greater, installed.
Warning: I had problems getting the Wireless Toolkit to work properly with JDK 5.0. If you don't
need the latest features in version 5.0, it is best to stick to any 1.4.2 version. I have used1.4.2_05 for all examples in this series.
ou need this Toolkit because it contains tools that are important in generating MIDlets. This Toolkit provide development environment for the MIDP 2.0 and CLDC 1.1 (and for MIDP 1.0 and CLDC 1.0, since thesrameters are backwards compatible), and it provides the optional packages required for the optionalraries, like 3D and Mobile Media applications. Lastly, it provides the ability to sign your MIDlets so that thn be authenticated before installation on a remote mobile device.
nce you download the installation package for the Toolkit, install it in the directory of your choice. The defWindows, is C:\WTK22, and this will be the installation directory for the examples in this series as well.
t explain the directories created under this folder just now. Before I do that, let us try and understand theocess of generating a MIDlet from scratch.
ages: 1, 2, 3 Next Pa
le:///C|/Documents%20and%20Settings/akanksha/j2me/j2me11.htm (3 of 3)7/14/2006 12:38:56 PM
http://today.java.net/pub/a/today/2005/02/09/j2me1.html?page=2http://today.java.net/pub/a/today/2005/02/09/j2me1.html?page=3http://today.java.net/pub/a/today/2005/02/09/j2me1.html?page=2http://today.java.net/pub/a/today/2005/02/09/j2me1.html?page=2http://today.java.net/pub/a/today/2005/02/09/j2me1.html?page=3http://today.java.net/pub/a/today/2005/02/09/j2me1.html?page=2 -
8/14/2019 The J2ME Big Index
6/97
ava.net: J2ME Tutorial, Part 1: Creating MIDlets
ME Tutorial, Part 1: Creating MIDlets
ages: 1, 2, 3
nderstanding the Process of MIDlet Creation--Without the Toolkit
ere are seven steps in the creation of a MIDlet. These steps are: designing, coding, compiling, preverificackaging, testing, and deployment. Some of these steps are not strictly MIDlet-centric (for example, every
plication needs to be designed, coded, and compiled), but we will cover them here because there are MID
ntric differences. The Toolkit abstracts a lot of these steps so that it is easier for you in the overall scheme
ngs. This is fine and dandy once you know the process, but when you are only starting out, you really shocoding by hand, rather than using a sugar-coated abstraction.
ensure that we get a hands-on understanding of these steps, let us take the help of a simple example. W
l create a MIDlet that, when executed, will print the current date and time on a mobile device for a short tim
ong with this in mind, keep Figure 2 handy to understand the sequence of these steps. Also, note that I wil
plain the lifecycle of MIDlets later. For the moment, let's get a simple MIDlet up and running, which willstrate these steps.
gure 2. Steps to MIDlet creation
tep 1: Design
Dlets are different from other applications that you may have created, simply because MIDlets run in an
vironment that is very different. There are several issues, not just those that are most visible (for example,
eractivity of your MIDlet with the user), but others that impact its usability.
r the example application, our Date-Time MIDlet does not need user interactivity. It needs to display the
le:///C|/Documents%20and%20Settings/akanksha/j2me/j2me12.htm (1 of 8)7/14/2006 12:38:59 PM
http://today.java.net/pub/a/today/2005/02/09/j2me1.html?page=1http://today.java.net/pub/a/today/2005/02/09/j2me1.html?page=3http://today.java.net/pub/a/today/2005/02/09/j2me1.html?page=3http://today.java.net/pub/a/today/2005/02/09/j2me1.html?page=1http://www.java.net/ -
8/14/2019 The J2ME Big Index
7/97
ava.net: J2ME Tutorial, Part 1: Creating MIDlets
rrent date and time for a few seconds when the user executes the MIDlet. For simple cases like this, it is
rhaps sufficient to mimic the design of the MIDlet by drawing it on a piece of paper. For more complex
signs with multiple screens, it is best to design the screens professionally before starting the actual codingocess.
tep 2: Code
ach MIDlet must extend the abstract MIDlet class found in the javax.microedition.midlet package
uch like creating an applet by extending the java.applet.Applet class. At the minimum, your MIDlet merride three methods of this abstract class, startApp(), pauseApp(), and destroyApp(boolean
conditional). Here is the DateTimeApp class:
ckage com.j2me.part1;
mport java.util.Date;
mport javax.microedition.lcdui.Alert;
mport javax.microedition.lcdui.Display;
mport javax.microedition.midlet.MIDlet;
blic class DateTimeApp extends MIDlet {
Alert timeAlert;
public DateTimeApp() {
timeAlert = new Alert("Alert!");
timeAlert.setString(new Date().toString());
}
public void startApp() {
Display.getDisplay(this).setCurrent(timeAlert);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
this example, DateTimeApp's constructor creates the element that is necessary to display the time on a
vice's screen and the startApp method does the actual task of displaying this element. Don't worry if you
n't understand how the Alert element works, or when the constructor or the other methods are called. I w
ver the former in the next part, when we look at the GUI elements of MIDP 2.0, and the latter later in this
icle in the MIDlet Lifecycle section.
opy this code into a file called DateTimeApp.javaand save it in a folder that mimics its package structure (me\part1). You can save it anywhere you want on your machine; as far as this article is concerned, we wil
le:///C|/Documents%20and%20Settings/akanksha/j2me/j2me12.htm (2 of 8)7/14/2006 12:38:59 PM
-
8/14/2019 The J2ME Big Index
8/97
ava.net: J2ME Tutorial, Part 1: Creating MIDlets
ve it in the folder C:\WTK22\article\com\j2me\part1.
tep 3: Compile
th this simple code in place, you now need to know how to compile it so that it is ready for mobile devices
ompiling MIDlets is not very much different from compiling normal Java applications. You still use javac a
e compiler, except you need to change the boot CLASSPATH while compiling MIDlets. This has the effect oanging the base Java classes that the Java compiler uses to compile your MIDlet against, thereby ensurin
at compilation is targeted towards the narrow set of Java's APIs for the J2ME platform. So instead of compainst the java.lang.Date in "normal" Java, you actually want compilation done for J2ME's java.lang
te. This is done by pointing to the CLDC and MIDP classes for javac's -bootclasspath option while
mpiling. This is shown below for the DateTimeApp MIDlet compilation. To do this compilation, make sure yat you enter the command by navigating to the directory C:\WTK22\articlevia the command prompt.
\WTK22\article>javac -bootclasspath ..\lib\cldcapi11.jar;..\lib\midpapi20.jar
2me\part1\DateTimeApp.java
otice that I have done the compilation against the CLDC API's 1.1 and MIDP API's 2.0 versions, respective
including these libraries in the bootclasspath option. I could have done the compilation against otherrsions if it was required, by simply pointing to their respective libraries.
tep 4: Preverify
efore you can deploy your MIDlet class, it needs to be preverified. Verification of byte code is a step perform
the JVM before it runs any class file to ensure that the class file is structurally and conceptually correct ase JVM specification. If the class file fails this check, it is rejected and the JVM shuts down, indicating either
curity or integrity violation of the class file. This verification is done by all JVMs, even the tiny JVM contain
a CLDC configuration for a J2ME device. Although this is not a problem for "normal" applications, verificat
J2ME devices is a resource and memory constraint that they simply cannot handle (or should not handle).erefore, the need for preverification.
everification is one part of a special two-step verification process, especially designed for constrained dev
ch as the ones running CLDC-based JVMs. The idea is to let a developer preverify his classes, which limit
e amount of work needed to be performed when the classes are verified in the device. This preverificationocess adds special information to the classes that identifies them as preverified and makes the process on
vice much more efficient.
eeping this in mind, preverify your Date-Time MIDlet. The Wireless Toolkit comes with a preverification tool
e bin folder of its installation (C:\WTK22\bin). The following command, when executed from C:\WTK22\artil preverify the DateTimeApp.classcreated in the previous step.
\WTK22\article>..\bin\preverify.exe -classpath ..\lib\cldcapi11.jar;..\lib
midpapi20.jar com.j2me.part1.DateTimeApp
y default, the preverifier will create the preverifiedversion of your DateTimeApp.classfile in a folder calledutputin the current directory. It will preserve the package structure, so your preverified class will now be in der C:\WTK22\article\output\com\j2me\part1\. You can, of course, point the output to another folder, using
le:///C|/Documents%20and%20Settings/akanksha/j2me/j2me12.htm (3 of 8)7/14/2006 12:38:59 PM
-
8/14/2019 The J2ME Big Index
9/97
ava.net: J2ME Tutorial, Part 1: Creating MIDlets
d option for the preverify tool, but for the moment, use the default output folder.
tep 5: Package
ackaging your MIDlet so that it ready for testing and deployment is a fairly involved process, with several st
hough each step is straightforward, they must be followed in proper sequence.
e first step is to create a Manifest file. This Manifest file describes the contents of the Java Archive (JAR) at we will be creating in the next step. There are several attributes that can go in this file, but for your Date-me MIDlet, stick to only the ones that are required. This file's contents are shown here:
Dlet-Name: DateTimeApp
Dlet-Version: 1.0.0
Dlet-Vendor: Vikram Goyal
ave this file as Manifest.mfin the C:\WTK22\article\outputfolder. (Note the newline after the last attribute,Dlet-Vendor. It must be present, otherwise this attribute will not be recognized.)
ext, create the JAR file that packages up the preverified DateTimeApp.classfile and the Manifest file. Toeate this JAR file, navigate to the C:\WTK22\article\outputdirectory and issue the following command:
\WTK22\article\output>jar cvfm DateTimeApp.jar Manifest.mf .\com
is will create the DateTimeApp.jarfile in the current (C:\WTK22\article\output) folder.
e second-to-last step is to create a file that has an extension of .jad. A Java Application Descriptor (JAD) fints to the location of the MIDlet it describes so that a J2ME device can install it. Again, this file can contai
veral attributes for a single MIDlet (or for several MIDlets), but for your Date-Time MIDlet, you will stick wite ones that are required.
Dlet-1: DateTimeApp, , com.j2me.part1.DateTimeApp
Dlet-Name: DateTimeApp
Dlet-Version: 1.0.0
Dlet-Vendor: Vikram Goyal
Dlet-Jar-URL: DateTimeApp.jar
Dlet-Jar-Size:
croEdition-Profile: MIDP-2.0
croEdition-Configuration: CLDC-1.1
ave this file as DateTimeApp.jadin the same folder as the JAR file (C:\WTK22\article\output). I will explain ributes in this file later, but for now, note that the value of the MIDlet-Jar-Size attribute is missing. Thi
ssing value brings you to the last step of the packaging step, where you determine the size of the
ateTimeApp.jarfile, and put that value in this JAD file, in actual bytes. It is very important to get this exactlyht, as the installation of this MIDlet will fail if this value is different from the actual size. On my machine, th
lue is 1469 bytes, and therefore, this is what this attribute looks like on my machine:
Dlet-Jar-Size: 1469
le:///C|/Documents%20and%20Settings/akanksha/j2me/j2me12.htm (4 of 8)7/14/2006 12:38:59 PM
-
8/14/2019 The J2ME Big Index
10/97
-
8/14/2019 The J2ME Big Index
11/97
ava.net: J2ME Tutorial, Part 1: Creating MIDlets
le:///C|/Documents%20and%20Settings/akanksha/j2me/j2me12.htm (6 of 8)7/14/2006 12:38:59 PM
-
8/14/2019 The J2ME Big Index
12/97
ava.net: J2ME Tutorial, Part 1: Creating MIDlets
gure 3. Testing the DateTimeApp
the lower right-hand corner of the emulated device's screen, you can see the "Launch" menu item listed. T
mulator has installed the MIDlet and is ready to launch it. Click on the phone button just underneath that mem and the MIDlet should display the current date time for a few seconds and then disappear. Note that the
Dlet is still running even after the date and time disappear, because in code, you did not destroy it.
tep 7: Deploy
is is it! Now you have reached the stage where you can deploy the MIDlet directly on your mobile device.
ere are two ways to do this. The first is via a network connection between your computer and your handse
is can either be via a USB cable or a Bluetooth wireless connection, depending on your device. Most Java
abled devices will allow you to install J2ME applications via this connection.
econd, and the one that is more interesting, because it opens up your MIDlet to the outside world, is via theernet. After all, what good is your MIDlet if the rest of the world cannot see it? Of course, this means that y
vice should be able to connect to the Internet using its internal browser.
efore you proceed further, recall that when you created the JAD file, you entered two attributes in it that
ecified the version of CLDC (1.1) and MIDP (2.0) for which the MIDlet was created. Since the DateTimeAp
Dlet does not use any of the features of these versions, it should theoretically run on devices that support wer versions of these attributes, as well. Therefore, the DateTimeApp MIDlet should run on CLDC 1.0 and
DP 1.0, but because the JAD file restricts these versions to the newer ones, devices will fail to install this
Dlet if they do not support these new versions. If this is the case with your device, fear not! As I said befor
cause we are not using any MIDP-2.0- or CLDC-1.1-specific features, you can simply change these versiombers in the JAD file, and this will be sufficient to install this device on all Java-enabled devices. If this is t
se with your device, or the device that you are going to test this MIDlet on, simply change these values in
AD file and you are good to go.
be able to deploy your MIDlet via the Internet, you need to have access to a web server with a real-world dress or domain name. You also need to have administrative privileges to be able to modify the configura
es of your web server to add some Multipurpose Internet Mail Exchange (MIME) types for the JAD and JAR
tensions. If you are using Jakarta/Tomcat as your web server, you don't need to do this, as it already has
ese MIME types. For the Apache web server, modify the mime.typesfile and add the following extension ty
xt/vnd.sun.j2me.app-descriptor jad
plication/java-archive jar
y adding these MIME types, you are informing the browser, or any client accessing these files from the servw to handle these files when they are downloaded into the device.
ext, create an HTML file that will become the point of reference. Strictly, this is not necessary, because a
vice that can access an HTML page can also access a JAD file. But an HTML page provides a point of
erence, and therefore, let's create one for your Date-Time MIDlet. The HTML doesn't need to be anything
ncy. Don't forget that users will be accessing this page via a mobile device, so it is prudent to keep the sizes page to the minimum. This is shown in Listing 2.
le:///C|/Documents%20and%20Settings/akanksha/j2me/j2me12.htm (7 of 8)7/14/2006 12:38:59 PM
-
8/14/2019 The J2ME Big Index
13/97
-
8/14/2019 The J2ME Big Index
14/97
ava.net: J2ME Tutorial, Part 1: Creating MIDlets
ME Tutorial, Part 1: Creating MIDlets
ages: 1, 2, 3
nderstanding the Process of MIDlet Creation--Using the Toolkit
the section Acquiring and Installing J2ME Development Kit above, you downloaded the Toolkit and instan the folder C:\WTK22(as far as this article series is concerned; you may have downloaded and installeda different folder). Let's explore the contents of this folder. Figure 4 shows these contents as they shouldw look on your machine.
gure 4. Wireless Toolkit folder contents
ote that the default installation of the Toolkit would not have created the articlefolder, and that you create
the previous section.
s far as a MIDlet developer is concerned, the most important folders are the appsand binfolders, but hershort summary of each of these folders.
le:///C|/Documents%20and%20Settings/akanksha/j2me/j2me13.htm (1 of 9)7/14/2006 12:39:01 PM
http://today.java.net/pub/a/today/2005/02/09/j2me1.html?page=1http://today.java.net/pub/a/today/2005/02/09/j2me1.html?page=2http://today.java.net/pub/a/today/2005/02/09/j2me1.html?page=2http://today.java.net/pub/a/today/2005/02/09/j2me1.html?page=1http://www.java.net/ -
8/14/2019 The J2ME Big Index
15/97
ava.net: J2ME Tutorial, Part 1: Creating MIDlets
olderame
Folder Description
ppdb Directory that acts as a simulation for mobile device file system
pps MIDlets created using the Toolkit reside in this directory
inContains executables for the various tools, including the Toolkititself, and various other tools like the preverifier and theemulator
ocsThe Wireless Toolkit documentation including APIdocumentation for MIDP 2.0 and MIDP 1.1
bContains the JAR files for MIDP (both 2.0 and 1.1), CLDC (both1.1 and 1.0) and several other optional libraries
essions Directory where network and profiling sessions are maintained
wtklibContains the libraries for the Toolkit itself, including theproperties of various device emulators
e appsfolder is the directory where all the MIDlets that are created using the Toolkit are installed. Browss folder, and you will notice several example MIDlets provided in their own folders. These have their ownectory structure that allows clean separation of source code, libraries, and rest of the files associated witDlet project.
e binfolder contains the executables for the Toolkit. The most important one is ktoolbar.exe (onndows), which starts the main interface window for the Toolkit. This folder contains other executables as
ell, some of which we came across earlier (for example, preverify.exe and emulator.exe). Let us,wever, concentrate on using the Toolkit now by running the ktoolbar.exe from the binfolder. The Tool start and you will get the window shown in Figure 5.
gure 5. Main Toolkit window
le:///C|/Documents%20and%20Settings/akanksha/j2me/j2me13.htm (2 of 9)7/14/2006 12:39:01 PM
-
8/14/2019 The J2ME Big Index
16/97
ava.net: J2ME Tutorial, Part 1: Creating MIDlets
s the message in the window says, from here, you can either create a new project or open an existing onehen you click on the Open Project menu button, you will be presented with a list of projects. As you mayve guessed, this list of projects is the directory listing of the appsfolder. Selecting a project from this list en up the project and allow you to change its settings, build it (which includes compilation, preverificationd packaging) and run it. The steps of designing and coding are still to be done outside of this Toolkit.
t's use the Toolkit to create the Date-Time MIDlet from the previous section. Click on New Project menu
tton, and enter the details in the window that comes up, as shown in Figure 6.
gure 6. Creating a new project
e next window that comes up will allow you to change settings that control the target platform of your MIthis case, you want to target this MIDlet towards the MIDP 2.0 and CLDC 1.1 platforms and therefore, ke
e Target Platform as JTWI, which preselects the MIDP 2.0 Profile. However, you will need to change theonfiguration to CLDC 1.1 and uncheck the Optional Mobile Media API library, as shown in Figure 7.
le:///C|/Documents%20and%20Settings/akanksha/j2me/j2me13.htm (3 of 9)7/14/2006 12:39:01 PM
-
8/14/2019 The J2ME Big Index
17/97
ava.net: J2ME Tutorial, Part 1: Creating MIDlets
gure 7. Changing project settings
ou can review the rest of the settings by clicking on the tabs at the top, but for the moment, your project isady to be created. Do so by clicking the OK button at the bottom. The project will be created with informaout where to place the project files displayed on the screen, as shown in Figure 8. You can verify that the
oolkit has created a DateTimeAppfolder under the appsfolder by navigating to it.
le:///C|/Documents%20and%20Settings/akanksha/j2me/j2me13.htm (4 of 9)7/14/2006 12:39:01 PM
-
8/14/2019 The J2ME Big Index
18/97
ava.net: J2ME Tutorial, Part 1: Creating MIDlets
gure 8. Project DateTimeApp created
ou have already created the only required src file for this MIDlet in the previous section. Copy this file,ateTimeApp.java, from the folder C:\WTK22\article\com\j2me\part1\ to the fully qualified srcfolder (C:\WTpps\DateTimeApp\src\com\j2me\part1 ). Note that the Toolkit created the fully qualified path based on theckage name, so you don't have to. Once the copy is done, come back to the Toolkit, and hit the Run mentton. The Toolkit will compile, preverify, and package, and, provided everything goes OK, will run the
ateTimeApp in the emulator. Seems simple enough, doesn't it? All you had to do was to create a new prot the settings, write the code, drop it in the right directory, and hit the Run button. The Toolkit took care ost.
efore you leave this section, examine the rest of the folders under the DateTimeApp project. The binfoldeder the DateTimeAppfolder contains the JAD and the Manifest files, while the classesfolder containsmpiled classes. But where is the JAR file for this MIDlet? Well, the JAR file is not created by just runningilding) your application in the Toolkit. To create the JAR file, you will need to select the Project menu itemd then select one of the options under the Package submenu, as shown in Figure 9.
le:///C|/Documents%20and%20Settings/akanksha/j2me/j2me13.htm (5 of 9)7/14/2006 12:39:01 PM
-
8/14/2019 The J2ME Big Index
19/97
ava.net: J2ME Tutorial, Part 1: Creating MIDlets
gure 9. Creating the MIDlet's JAR file
y creating this package, the JAR file will be created, with correct Manifest information in the JAD file. Youen create the HTML file that we created in the deploy section previously, by clicking on the Run via OTAver The Air) menu. This will not only allow you to simulate your emulator running this MIDlet via the Intert also create the HTML file for you in the binfolder. Before you can use this HTML file to deploy on your rver, along with the JAD and the JAR files, you will need to change the hostname, which defaults tocalhost."
ou now know how to create a simple MIDlet, both using the Toolkit, and without it. It's now time to look at Dlet lifecycle to understand what actually happens when your MIDlet is deployed and run.
he MIDlet Lifecycle
obile devices, whether emulators or real, interact with a MIDlet using their own software, which is calledpplication Management Software (AMS). The AMS is responsible for initializing, starting, pausing, resumid destroying a MIDlet. (Besides these services, AMS may be responsible for installing and removing aDlet, as well.) To facilitate this management, a MIDlet can be in one of three states which is controlled ve MIDlet class methods, that every MIDlet extends and overrides. These states are active, paused andstroyed.
le:///C|/Documents%20and%20Settings/akanksha/j2me/j2me13.htm (6 of 9)7/14/2006 12:39:01 PM
-
8/14/2019 The J2ME Big Index
20/97
ava.net: J2ME Tutorial, Part 1: Creating MIDlets
gure 10. The possible states of a MIDlet and the transition between them
s you can see from Figure 11, an installed MIDlet is put into a paused state by the AMS creating an instanit, by calling its no-args constructor. This is of course, not the only way that the MIDlet can be in a paus
ate. It can enter this state when the AMS calls the pauseApp() method on an active MIDlet (and the meturns successfully). It can also enter this state when the MIDlet pauses itself by calling the notifyPause
method, as opposed to the pauseApp() method, which is called by the AMS. However, what exactly isppening with the MIDlet in the paused state?
a paused state, the MIDlet is waiting for a chance to get into the active state. Theoretically, in this state, ould not be holding or using any of the device resources and should be passive in nature. Once the MIDleated, this is the state to be in before becoming active. Also, entering the paused state is necessary whee device requires it to consume fewer resources, because these resources may be required for handlingher device functions, like handling an incoming call. This is when the device invokes the pauseApp()ethod through the AMS. If the MIDlet should inform the AMS that it has paused, it should invoke theotifyPaused() method, which tells the AMS that the MIDlet has indeed paused.
le:///C|/Documents%20and%20Settings/akanksha/j2me/j2me13.htm (7 of 9)7/14/2006 12:39:01 PM
-
8/14/2019 The J2ME Big Index
21/97
ava.net: J2ME Tutorial, Part 1: Creating MIDlets
ne final way in which a MIDlet can get into a paused state is when the MIDlet's startApp() method, whcalled when the AMS invokes it to start the MIDlet (either the first time or from a paused state), throws aDletStateChangeException. Essentially, in case of an error, the MIDlet takes the safe road of stayithe paused state.
e active state is where every MIDlet wants to be! This is when the MIDlet can do its functions, hold thevice resources and generally, do what it is supposed to do. As said previously, a MIDlet is in an active st
hen the AMS calls the startApp() method on a paused MIDlet (actually, the MIDlet enters the active st
st beforethis method is called by the AMS). A paused MIDlet can request to go into the active state bylling the method resumeRequest(), which informs the AMS that the MIDlet wishes to become active. T
MS may of course, choose to ignore this request or, alternatively, queue it if there are other MIDletsquesting the same.
e destroyed state is entered when a MIDlet's destroyApp(boolean unconditional) method is cad returns successfully, either from an active or paused state. This method is called by the AMS when it f
at there is no need for the MIDlet to keep running and is the place the MIDlet may perform cleanup and ost minute activities. The MIDlet can enter this state itself, by calling the notifyDestroyed() method, worms the AMS that the MIDlet has cleaned up its resources and is eligible for destruction. Of course, sinc
s case, the destroyApp(boolean unconditional) method is not called by the AMS, any last-minutivities must be done before this method is invoked.
hat happens if the AMS calls the destroyApp(boolean unconditional) method in the middle of aportant step that the MIDlet may be doing, and may be loath to be destroyed? This is where the Booleannconditional flag comes into the picture. If this flag is set to true, the MIDlet will be destroyed, irrespecwhat the MIDlet is doing. However, if this flag is false, effectively, the AMS is telling the MIDlet that it wa
e MIDlet to be destroyed, but if the MIDlet is doing something important, it can raise aDletStateChangeException, and the AMS will not destroy it just yet. However, note that even then,
ere are no guarantees that the MIDlet will not be destroyed, and it remains up to each device to decide hoey should handle the request. If the device does honor the MIDlet's request, it may try and invoke thestroyApp(boolean unconditional) at a later stage.
ote that a destroyed state means that the MIDlet instancehas been destroyed, but not uninstalled from thvice. The MIDlet remains installed in the device, and a new instance of it may be created later.
t me end this section, and this article, with a flow chart of a typical sequence of events while using theateTimeApp MIDlet that we created in the previous sections, and the corresponding AMS actions and MIates. This flow chart is shown in Figure 11.
le:///C|/Documents%20and%20Settings/akanksha/j2me/j2me13.htm (8 of 9)7/14/2006 12:39:01 PM
-
8/14/2019 The J2ME Big Index
22/97
ava.net: J2ME Tutorial, Part 1: Creating MIDlets
gure 11. AMS actions and MIDlet states through a sequence of events
the next part of this series, you will start creating useful MIDlets by understanding the User Interface APDP 2.0. This will allow you to create powerful user interfaces, a key requirement for any MIDlet.
kram Goyalis the author of Pro Java ME MMAPI.
le:///C|/Documents%20and%20Settings/akanksha/j2me/j2me13.htm (9 of 9)7/14/2006 12:39:01 PM
http://today.java.net/pub/au/179http://today.java.net/pub/au/179 -
8/14/2019 The J2ME Big Index
23/97
ava.net: J2ME Tutorial, Part 2: User Interfaces with MIDP 2.0
J2ME Tutorial, Part 2: User Interfaces with MIDP 2.0by Vikram Goyal
05/03/2005
is is part two in a series that explores J2ME with MIDP 2.0. "Part 1: Creating MIDlets" showed you how to
quire, install, and use the Wireless Toolkit for developing MIDlets. Part one also showed how to develop
Dlets without using the Toolkit, which is important in order to understand the behind-the-scenes activityvolved in creating a MIDlet. Part one finished with an exploration of the lifecycle of a MIDlet, with a step-by
ep guide through the events in the life of a MIDlet.
this article, you will create the user interface (UI) elements of a MIDlet. Since the interaction with a user is ramount concern in any MIDlet, due to the size of the screens, it is important for you to understand the ba
this side of MIDlets. Any interaction with a user is done via a UI element. In fact, when you created the
mplistic Date-Time MIDlet in part one, you used one such element called Alert to show an alert message
e screen. This message was actually shown on the screen by the help of another UI element called Displ
t's start with a discussion of the overall architecture of the UI elements.
ser Interface Architecture
DP 2.0 provides UI classes in two packages, javax.microedition.lcdui and javax.microeditio
dui.game, where lcdui stands for liquid crystal display user interface (LCD UI). As expected, the game
ckage contains classes for development of a wireless game UI. I will discuss this package in the next part
s series.
e UI classes of of MIDP 2.0's javax.microedition.lcdui package can be divided into two logical
oups: the high- and low-level groups. The classes of the high-level group are perfect for development ofDlets that target the maximum number of devices, because these classes do not provide exact control ove
eir display. The high-level classes are heavily abstracted to provide minimal control over their look and feehich is left for device on which they are deployed to manage, according to its capabilities. These classes ar
own in Figure 1.
le:///C|/Documents%20and%20Settings/akanksha/j2me/midletUI1.htm (1 of 6)7/14/2006 12:39:02 PM
http://today.java.net/pub/au/179http://today.java.net/pub/a/today/2005/02/09/j2me1.htmlhttp://today.java.net/pub/a/today/2005/02/09/j2me1.htmlhttp://today.java.net/pub/au/179http://www.java.net/ -
8/14/2019 The J2ME Big Index
24/97
ava.net: J2ME Tutorial, Part 2: User Interfaces with MIDP 2.0
gure 1. High-level MIDP 2.0 UI classes
e classes of the low-level group are perfect for MIDlets where precise control over the location and displaye UI elements is important and required. Of course, with more control comes less portability. If your MIDlet
veloped using these classes, it may not be deployable on certain devices, because they require precise
ntrol over the way they look and feel. There are only two classes in this group, and they are shown in Figu
gure 2. Low-level MIDP 2.0 UI classes
ere is another class in the low-level group called GameCanvas, which is not shown here, as it will be
scussed in the next part of this series.
r you to be able to show a UI element on a device screen, whether high- or low-level, it must implement th
splayable interface. A displayable class may have a title, a ticker, and certain commands associated w
mong other things. This implies that both the Screen and Canvas classes and their subclasses implemen
erface, as can be seen in Figure 3. The Graphics class does not implement this interface, because it dea
th low-level 2D graphics that directly manipulate the device's screen.
gure 3. Canvas andScreen implement theDisplayable interface
Displayable class is a UI element that can be shown on the device's screen while the Display class
stracts the display functions of an actual device's screen and makes them available to you. It providesethods to gain information about the screen and to show or change the current UI element that you want
le:///C|/Documents%20and%20Settings/akanksha/j2me/midletUI1.htm (2 of 6)7/14/2006 12:39:02 PM
-
8/14/2019 The J2ME Big Index
25/97
ava.net: J2ME Tutorial, Part 2: User Interfaces with MIDP 2.0
splayed. Thus, a MIDlet shows a Displayable UI element on a Display using the setCurrent
isplayable element) method of the Display class.
the method name suggests, the Display can have only one Displayable element at one time, which
comes the current element on display. The current element that is being displayed can be accessed using
ethod getCurrent(), which returns an instance of a Displayable element. The static method
tDisplay(MIDlet midlet) returns the current display instance associated with your MIDlet method.
ittle bit of actual code here would go a long way in helping understand the MIDlet UI concepts that we havst discussed. Rather than write new code, let's try and retrofit our understanding on the Date-Time MIDlet
ample from part one, which is reproduced in Listing 1.
ckage com.j2me.part1;
mport java.util.Date;
mport javax.microedition.lcdui.Alert;
mport javax.microedition.lcdui.Display;
mport javax.microedition.midlet.MIDlet;
blic class DateTimeApp extends MIDlet {
Alert timeAlert;
public DateTimeApp() {
timeAlert = new Alert("Alert!");
timeAlert.setString(new Date().toString());
}
public void startApp() {
Display.getDisplay(this).setCurrent(timeAlert);
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {
}
sting 1. DateTimeApp MIDlet
Displayable UI element, an Alert, is created in the constructor. When the device's Application
le:///C|/Documents%20and%20Settings/akanksha/j2me/midletUI1.htm (3 of 6)7/14/2006 12:39:02 PM
-
8/14/2019 The J2ME Big Index
26/97
ava.net: J2ME Tutorial, Part 2: User Interfaces with MIDP 2.0
anagement Software (AMS) calls the startApp() method, the current display available for this MIDlet is
tracted using the Display.getDisplay() method. The Alert is then made the current item on display
tting it as a parameter to the setCurrent() method.
seen from Figure 1, there are four high-level UI elements that can be displayed on a MIDlet's screen. Let'scuss each of these elements in detail.
ert
ou already know how to create a basic alert message from Listing 1. Alerts are best used in informational o
ror messages that stay on the screen for a short period of time and then disappear. You can control severa
pects of an alert by calling the relevant methods or using the right constructor.
q The title must be set while creating the alert and it cannot be changed afterwards: Alert
("Confirm?");.
q To set the message the alert displays use, setString("Message to display") or pass the
message as part of the constructor, Alert( "Confirm", "Are you sure?", null, null);
q Use setTimeout(int time) to set the time (in milliseconds) for which the alert is displayed on the
screen. If you pass Alert.FOREVER as the value of time, you will show the alert forever and makealert a modal dialog.
q There are five types of alerts defined by the class AlertType: ALARM, CONFIRMATION, ERROR, INF
and WARNING. These have different looks and feels and can have a sound played along with the aler
q Associate an image with the alert using the method setImage(Image img);.
q Set an indicator with the alert using setIndicator(Gauge gauge); method.
st
ist contains one or more choices (elements), which must have a text part, an optional image part, and an
tional font for the text part. The List element implements the Choice interface, which defines the basicerations of this element. The list must itself have a title, and must define a policy for the selection of its
ements. This policy dictates whether only one element can be selected (Choice.EXCLUSIVE), multiple
ements can be selected (Choice.MULTIPLE), or the currently highlighted element is selected (Choice.
MPLICIT). Figure 4 shows the difference between the three selection policies.
le:///C|/Documents%20and%20Settings/akanksha/j2me/midletUI1.htm (4 of 6)7/14/2006 12:39:02 PM
-
8/14/2019 The J2ME Big Index
27/97
ava.net: J2ME Tutorial, Part 2: User Interfaces with MIDP 2.0
gure 4. Selection policies forList elements
ou can create a list in one of two ways.
q Create an list that contains no elements, and then append or insert individual elements.
q Create the elements beforehand and then create a list with these elements.
sting 2 shows both ways.
ckage com.j2me.part2;
mport javax.microedition.lcdui.List;
mport javax.microedition.lcdui.Choice;
mport javax.microedition.lcdui.Display;
mport javax.microedition.midlet.MIDlet;
blic class ListExample extends MIDlet {
List fruitList1;
List fruitList2;
public ListExample() {
fruitList1 = new List("Select the fruits you like",
Choice.MULTIPLE);
fruitList1.append("Orange", null);
fruitList1.append("Apple", null);
fruitList1.insert(1, "Mango", null);
// inserts between Orange and Apple
String fruits[] = {"Guava", "Berry", "Kiwifruit"};
le:///C|/Documents%20and%20Settings/akanksha/j2me/midletUI1.htm (5 of 6)7/14/2006 12:39:02 PM
-
8/14/2019 The J2ME Big Index
28/97
-
8/14/2019 The J2ME Big Index
29/97
-
8/14/2019 The J2ME Big Index
30/97
ava.net: J2ME Tutorial, Part 2: User Interfaces with MIDP 2.0
txtBox1 = new TextBox(
"Your Name?", "", 50, TextField.ANY);
txtBox2 = new TextBox(
"Your PIN?",
"",
4,
TextField.NUMERIC | TextField.PASSWORD);
}
public void startApp() {
Display display = Display.getDisplay(this);
display.setCurrent(txtBox1);
try{
Thread.currentThread()Sleep(5000);
} catch(Exception e) {}
txtBox1.setString("Bertice Boman");
try{
Thread.currentThread()Sleep(3000);
} catch(Exception e) {}
// inserts 'w' at the 10th index to make the
// name Bertice Bowman
txtBox1.insert("w", 10);
try{
Thread.currentThread()Sleep(3000);
} catch(Exception e) {}
display.setCurrent(txtBox2);
}
public void pauseApp() {
}
public void destroyApp(Boolean unconditional) {
}
sting 3. UsingTextBoxes
e listing creates two textboxes: one that accepts anything under 50 characters, and one that accepts only meric characters that are not shown on the screen. If you try entering anything other than numbers in the
meric-only box, the device will not accept it, but the actual behavior may vary across actual devices.
orm
le:///C|/Documents%20and%20Settings/akanksha/j2me/midletUI2.htm (2 of 6)7/14/2006 12:39:04 PM
-
8/14/2019 The J2ME Big Index
31/97
ava.net: J2ME Tutorial, Part 2: User Interfaces with MIDP 2.0
form is a collections of instances of the Item interface. The TextBox class (discussed in the preceding
ction) is a standalone UI element, while the TextFieldisan Item instance. Essentially, a textbox can bown on a device screen without the need for a form, but a text field requires a form.
n item is added to a form using the append(Item item) method, which simply tacks the added item to thttom of the form and assigns it an index that represents its position in the form. The first added item is at in
the second at index 1, and so on. You can also use the insert(int index, Item newItem) method
sert an item at a particular position or use set(int index, Item newItem) to replacean item at articular position specified by the index.
ere are eight Item types that can be added to a form.
1. StringItem: A label that cannot be modified by the user. This item may contain a title and text, bot
which may be null to allow it to act as a placeholder. The Form class provides a shortcut for adding a
StringItem, without a title: append(String text)
2. DateField: Allows the user to enter date/time in one of three formats: DATE, TIME, or DATE_TIME
3. TextField: Same as a TextBox.
4. ChoiceGroup: Same as a List.5. Spacer: Used for positioning UI elements by putting some space between them. This element is an
invisible UI element and can be set to a particular size.
6. Gauge: A gauge is used to simulate a progress bar. However, this progress bar look can also be use
an interactive mode by the user. For example, if you wanted to show the user a volume control, a gau
would be used to show an interactive knob.
7. ImageItem: An item that holds an image! Like the StringItem, the Form class provides a shortcu
method for adding an image: append(Image image). More about images in a later section.
8. CustomItem: CustomItem is an abstract class that allows the creation of subclasses that have the
own appearances, their own interactivity, and their own notification mechanisms. If you require a UI
element that is different from the supplied elements, you can subclass CustomItem to create it for
addition to a form.
ese items (except CustomItem) can be seen in Figure 5, and the corresponding code is shown in ListingOTE: The image, duke.gif, should be kept in the resfolder of this MIDlet application.)
ckage com.j2me.part2;
mport javax.microedition.lcdui.Form;
mport javax.microedition.lcdui.Gauge;
mport javax.microedition.lcdui.Spacer;
mport javax.microedition.lcdui.ImageItem;
mport javax.microedition.lcdui.TextField;
mport javax.microedition.lcdui.DateField;
mport javax.microedition.lcdui.StringItem;
mport javax.microedition.lcdui.ChoiceGroup;
mport javax.microedition.lcdui.Image;
mport javax.microedition.lcdui.Choice;
mport javax.microedition.lcdui.Display;
le:///C|/Documents%20and%20Settings/akanksha/j2me/midletUI2.htm (3 of 6)7/14/2006 12:39:04 PM
-
8/14/2019 The J2ME Big Index
32/97
ava.net: J2ME Tutorial, Part 2: User Interfaces with MIDP 2.0
mport javax.microedition.midlet.MIDlet;
blic class FormExample extends MIDlet {
private Form form;
private Gauge gauge;
private Spacer spacer;
private ImageItem imageItem;
private TextField txtField;
private DateField dateField;
private StringItem stringItem;
private ChoiceGroup choiceGroup;
public FormExample() {
form = new Form("Your Details");
// a StringItem is not editable
stringItem = new StringItem("Your Id: ", "WXP-890");
form.append(stringItem);
// you can accept Date, Time or DateTime formats
dateField = new DateField("Your DOB: ", DateField.DATE);
form.append(dateField);
// similar to using a TextBox
txtField = new TextField(
"Your Name: ", "", 50, TextField.ANY);
form.append(txtField);
// similar to using a List
choiceGroup = new ChoiceGroup("Your meals: ",
Choice.EXCLUSIVE,
new String[] {"Veg", "Non-Veg"},
null);
form.append(choiceGroup);
// put some space between the items to segregate
spacer = new Spacer(20, 20);
form.append(spacer);
// a gauge is used to show progress
gauge = new Gauge("Step 1 of 3", false, 3, 1);
form.append(gauge);
// an image may not be found,
// therefore the Exception must be handled
// or ignored
try {
imageItem = new ImageItem(
"Developed By: ",
le:///C|/Documents%20and%20Settings/akanksha/j2me/midletUI2.htm (4 of 6)7/14/2006 12:39:04 PM
-
8/14/2019 The J2ME Big Index
33/97
ava.net: J2ME Tutorial, Part 2: User Interfaces with MIDP 2.0
Image.createImage("/duke.gif"),
ImageItem.LAYOUT_DEFAULT,
"DuKe");
form.append(imageItem);
} catch(Exception e) {}
}
public void startApp() {
Display display = Display.getDisplay(this);
display.setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(Boolean unconditional) {
}
sting 4. Using forms
le:///C|/Documents%20and%20Settings/akanksha/j2me/midletUI2.htm (5 of 6)7/14/2006 12:39:04 PM
-
8/14/2019 The J2ME Big Index
34/97
ava.net: J2ME Tutorial, Part 2: User Interfaces with MIDP 2.0
gure 5. The elements of a form
ages: 1, 2, 3, 4 Next Pa
le:///C|/Documents%20and%20Settings/akanksha/j2me/midletUI2.htm (6 of 6)7/14/2006 12:39:04 PM
http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=1http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=3http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=4http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=3http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=3http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=4http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=3http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=1 -
8/14/2019 The J2ME Big Index
35/97
ava.net: J2ME Tutorial, Part 2: User Interfaces with MIDP 2.0
ME Tutorial, Part 2: User Interfaces with MIDP 2.0
ages: 1, 2, 3, 4
mages, Tickers, and Gauges
sing images, tickers, and gauges as UI elements in MIDlets is quite straightforward. A gauge, as you saw ie last section, is an item that can only be displayed on a form to indicate progress or to control a MIDlet
ature (like volume). A ticker, on the other hand, can be attached to any UI element that extends the
splayable abstract class, and results in a running piece of text that is displayed across the screenhenever the element that is attached to it is shown on the screen. Finally, an image, can be used with vario
elements, including a form, as we saw in the last section.
nce the ticker can be used with all displayable elements, it provides a handy way to display information abo
e current element on the screen. The Displayable class provides the method setTicker(Ticker
cker), and the ticker can itself be created using its constructor Ticker(String msg), with the messag
at you want the ticker to display. By using setString(String MSG), you can change this message, and
s change is effected immediately. For example, the form used in the previous section can have its own tick
splayed by setting form.setTicker(new Ticker("Welcome to Vandalay Industries!!!")). Tl result in a ticker across the top of the screen (in the Toolkit's emulator), while the user is filling out the for
is is shown in Figure 6.
gure 6. Setting aTicker on aDisplayable
the previous section, we saw an example of a gauge in a non-interactive mode. It was there to represent t
ogress of a form being filled out by the MIDlet user. A non-interactive gauge can be used to represent the
ogress of a certain task; for example, when the device may be trying to make a network connection or readdatastore, or when the user is filling out a form. In the previous section, we created a gauge by specifying f
lues. The label ("Step 1 of 3"), the interactive mode (false), the maximum value (3) and the initial value (1)
owever, when you don't know how long a particular activity is going to take, you can use the value of
NDEFINITE for the maximum value.
non-interactive gauge that has an INDEFINITE maximum value acquires special meaning. (You cannot
eate an interactivegauge with an INDEFINITE maximum value.) This type of gauge can be in one of fourates, and this is reflected by the initial value (which is also the current value of the gauge). These states ar
le:///C|/Documents%20and%20Settings/akanksha/j2me/midletUI3.htm (1 of 8)7/14/2006 12:39:06 PM
http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=1http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=2http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=4http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=4http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=2http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=1http://www.java.net/ -
8/14/2019 The J2ME Big Index
36/97
ava.net: J2ME Tutorial, Part 2: User Interfaces with MIDP 2.0
NTINUOUS_IDLE, INCREMENTAL_IDLE, CONTINUOUS_RUNNING, and INCREMENTAL_UPDATING . Eachate represents the best effort of the device to let the user know the current activity of the MIDlet, and you c
e them to represent these states yourself. Listing 5 shows an example of using these non-interactive gaug
ong with an example of an interactive gauge. Remember that a Gauge is a UI Item, and therefore, can on
displayed as part of a Form.
ckage com.j2me.part2;
mport javax.microedition.lcdui.Form;
mport javax.microedition.lcdui.Gauge;
mport javax.microedition.lcdui.Display;
mport javax.microedition.midlet.MIDlet;
blic class GaugeExample extends MIDlet {
private Form form;
private Gauge niIndefinate_CI;
private Gauge niIndefinate_II;
private Gauge niIndefinate_CR;
private Gauge niIndefinate_IU;
private Gauge interactive;
public GaugeExample() {
form = new Form("Gauge Examples");
niIndefinate_CI =
new Gauge(
"NI - Cont Idle",false,
Gauge.INDEFINITE,
Gauge.CONTINUOUS_IDLE);
form.append(niIndefinate_CI);
niIndefinate_II =
new Gauge(
"NI - Inc Idle",
false,
Gauge.INDEFINITE,
Gauge.INCREMENTAL_IDLE);form.append(niIndefinate_II);
niIndefinate_CR =
new Gauge(
"NI - Cont Run",
false,
Gauge.INDEFINITE,
Gauge.CONTINUOUS_RUNNING);
form.append(niIndefinate_CR);
le:///C|/Documents%20and%20Settings/akanksha/j2me/midletUI3.htm (2 of 8)7/14/2006 12:39:06 PM
-
8/14/2019 The J2ME Big Index
37/97
ava.net: J2ME Tutorial, Part 2: User Interfaces with MIDP 2.0
niIndefinate_IU =
new Gauge(
"NI - Inc Upd",
false,
Gauge.INDEFINITE,
Gauge.INCREMENTAL_UPDATING);
form.append(niIndefinate_IU);
interactive =
new Gauge(
"Interactive ",
true,
10,
0);
form.append(interactive);
}
public void startApp() {Display display = Display.getDisplay(this);
display.setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(Boolean unconditional) {
}
sting 5. UsingGauges
ach mobile device will use its own set of images to represent these gauges. This will, in all probability, be
ferent from the gauges that you will see if you run this listing in the Emulator supplied with the Toolkit.
ou can also associate an image with an Alert and a Choice-based UI element. When an image is createher by reading from a physical location or by making an image in-memory, it exists only in the off-screen
emory. You should, therefore, be careful while using images, and restrict the size of images to the minimum
ssible to avoid filling the device's available memory.
e Image class provides several static methods to create or acquire images for use in MIDlets. An image t
created in-memory, by using the createImage(int width, int height) method, is mutable, which
eans that you can edit it. An image created this way initially has all of its pixels set to white, and you can
quire a graphics object on this image by using the method getGraphics() to modify the way it is render
screen. More about the Graphics object follows in the low-level API section.
acquire an immutable image, you can use one of two methods: createImage(String imageName) o
le:///C|/Documents%20and%20Settings/akanksha/j2me/midletUI3.htm (3 of 8)7/14/2006 12:39:06 PM
-
8/14/2019 The J2ME Big Index
38/97
ava.net: J2ME Tutorial, Part 2: User Interfaces with MIDP 2.0
eateImage(InputStream stream). The first method is used for looking up images from an associate
ckaged .jar file, while the second method is good for reading an image over a network. To create an
mutable image from in-memory data, you can either use createImage(byte[] imageData, int
mageOffset, int imageLength) or createImage(Image source). The first method allows you torm an image out of a byte array representation, while the second allows the creation of an image from an
isting image.
ote that the MIDlet specification mandates support for the Portable Network Graphics (PNG) format for
ages. Thus, all devices that support MIDlets will display a *.png image. These devices may support otherrmats, especially GIF and JPEG formats, but that is not a guarantee.
ou have already seen an example of acquiring an image in the section on forms. In Listing 4, an image was
apped up in an ImageItem class so that it could be displayed in a form. The image was kept in the resfothe MIDlet for the Toolkit and the Emulator to find. The createImage(String imageName) method us
e Class.getResourceAsStream(String imageName) method to actually locate this image. The Too
kes care of packaging this image in the right folder when you create a ,jar file. In this case, this will be the t
vel .jar folder. Make sure that whenever you reference images in your MIDlets that the images are kept in t
ht location. For example, if you want to keep all of your images for a MIDlet in an imagefolder in the final
ckaged .jar file, and not the top-level .jar folder, you will need to keep these images under an imagefolderder the resfolder itself. To reference any of these images, you will need to ensure that you reference thems imagesfolder. For example: createImage("/images/duke.gif"); will reference the image duke.gder the imagesfolder.
andling User Commands
one of the UI elements so far have allowed any interaction from the user! A MIDlet interacts with a userrough commands. A command is the equivalent of a button or a menu item in a normal application, and ca
ly be associated with a displayable UI element. Like a ticker, the Displayable class allows the user to
ach a command to it by using the method addCommand(Command command). Unlike a ticker, a displayaelement can have multiple commands associated with it.
e Command class holds the information about a command. This information is encapsulated in four properese properties are: a short label, an optional long label, a command type, and a priority. You create a
mmand by providing these values in its constructor:
mmand exitCommand = new Command("EXIT", Command.EXIT, 1);
ote that commands are immutable once created.
y specifying the type of a command, you can let the device running the MIDlet map any predefined keys on
vice to the command itself. For example, a command with the type OK will be mapped to the device's OK k
e rest of the types are: BACK, CANCEL, EXIT, HELP, ITEM, SCREEN, and STOP. The SCREEN type relates
application-defined command for the current screen. Both SCREEN and ITEM will probably never have an
vice-mapped keys.
y specifying a priority, you tell the AMS running the MIDlet where and how to show the command. A lower
lue for the priority is of higher importance, and therefore indicates a command that the user should be ablevoke directly. For example, you would probably always have an exit command visible to the user and give
le:///C|/Documents%20and%20Settings/akanksha/j2me/midletUI3.htm (4 of 8)7/14/2006 12:39:06 PM
http://www.ietf.org/rfc/rfc2083.txthttp://www.ietf.org/rfc/rfc2083.txt -
8/14/2019 The J2ME Big Index
39/97
ava.net: J2ME Tutorial, Part 2: User Interfaces with MIDP 2.0
ority of 1. Since the screen space is limited, the device then bundles less-important commands into a men
e actual implementation varies from device to device, but the most likely scenario involves one priority-1
mmand displayed along with an option to see the other commands via a menu. Figure 7 shows this likelyenario.
gure 7. The way commands are displayed. The menu pops up when the user presses the key correspondithe menu command.
e responsibility for acting on commands is performed by a class implementing the CommandListener
erface, which has a single method: commandAction(Command com, Displayable dis). However,fore command information can travel to a listener, The listener is registered with the method
tCommandListener(CommandListener listener) from the Displayable class.
utting this all together, Listing 6 shows how to add some commands to the form discussed in Listing 4.
ckage com.j2me.part2;
mport javax.microedition.lcdui.Form;
mport javax.microedition.lcdui.Gauge;
mport javax.microedition.lcdui.Spacer;
mport javax.microedition.lcdui.ImageItem;
mport javax.microedition.lcdui.TextField;
mport javax.microedition.lcdui.DateField;
mport javax.microedition.lcdui.StringItem;
mport javax.microedition.lcdui.ChoiceGroup;
mport javax.microedition.lcdui.Image;
mport javax.microedition.lcdui.Choice;
mport javax.microedition.lcdui.Display;
mport javax.microedition.lcdui.Command;
mport javax.microedition.midlet.MIDlet;
le:///C|/Documents%20and%20Settings/akanksha/j2me/midletUI3.htm (5 of 8)7/14/2006 12:39:06 PM
-
8/14/2019 The J2ME Big Index
40/97
ava.net: J2ME Tutorial, Part 2: User Interfaces with MIDP 2.0
mport javax.microedition.lcdui.Displayable;
mport javax.microedition.lcdui.CommandListener;
blic class FormExample
extends MIDlet
implements CommandListener {
private Form form;
private Gauge gauge;
private Spacer spacer;
private ImageItem imageItem;
private TextField txtField;
private DateField dateField;
private StringItem stringItem;
private ChoiceGroup choiceGroup;
public FormExample() {
form = new Form("Your Details");
// a StringItem is not editable
stringItem = new StringItem("Your Id: ", "WXP-890");
form.append(stringItem);
// you can accept Date, Time or DateTime formats
dateField =
new DateField("Your DOB: ", DateField.DATE);
form.append(dateField);
// similar to using a TextBox
txtField = new TextField("Your Name: ", "", 50, TextField.ANY);
form.append(txtField);
// similar to using a List
choiceGroup = new ChoiceGroup(
"Your meals: ",
Choice.EXCLUSIVE,
new String[] {"Veg", "Non-Veg"},
null);
form.append(choiceGroup);
// put some space between the items
spacer = new Spacer(20, 20);
form.append(spacer);
// a gauge is used to show progress
gauge = new Gauge("Step 1 of 3", false, 3, 1);
form.append(gauge);
// an image may not be found,
le:///C|/Documents%20and%20Settings/akanksha/j2me/midletUI3.htm (6 of 8)7/14/2006 12:39:06 PM
-
8/14/2019 The J2ME Big Index
41/97
ava.net: J2ME Tutorial, Part 2: User Interfaces with MIDP 2.0
// therefore the Exception must be handled
// or ignored
try {
imageItem = new ImageItem(
"Developed By: ",
Image.createImage("/duke.gif"),
ImageItem.LAYOUT_DEFAULT,
"Duke");
form.append(imageItem);
} catch(Exception e) {}
// create some commands and add them
// to this form
form.addCommand(
new Command("EXIT", Command.EXIT, 2));
form.addCommand(
new Command("HELP", Command.HELP, 2));
form.addCommand(
new Command("OK", Command.OK, 1));
// set itself as the command listener
form.setCommandListener(this);
}
// handle commands
public void commandAction(
Command com, Displayable dis) {
String label = com.getLabel();
if("EXIT".equals(label))notifyDestroyed();
else if("HELP"Equals(label))
displayHelp();
else if("OK"Equals(label))
processForm();
}
public void displayHelp() {
// show help
}
public void processForm() {
// process Form
}
public void startApp() {
Display display = Display.getDisplay(this);
display.setCurrent(form);
}
le:///C|/Documents%20and%20Settings/akanksha/j2me/midletUI3.htm (7 of 8)7/14/2006 12:39:06 PM
-
8/14/2019 The J2ME Big Index
42/97
ava.net: J2ME Tutorial, Part 2: User Interfaces with MIDP 2.0
public void pauseApp() {
}
public void destroyApp(Boolean unconditional) {
}
sting 6. Adding commands to a form
e differences from Listing 4 are highlighted in bold. The command listener in this case is the form class its
d therefore, it implements the commandAction() method. Note that this method also accepts a displaya
rameter, which is very useful. Because commands are immutable, they can be attached to multiple
splayable objects, and this parameter can help distinguish which displayable object invoked the command
ages: 1, 2, 3, 4 Next Pa
le:///C|/Documents%20and%20Settings/akanksha/j2me/midletUI3.htm (8 of 8)7/14/2006 12:39:06 PM
http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=1http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=2http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=4http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=4http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=4http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=4http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=2http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=1 -
8/14/2019 The J2ME Big Index
43/97
ava.net: J2ME Tutorial, Part 2: User Interfaces with MIDP 2.0
ME Tutorial, Part 2: User Interfaces with MIDP 2.0
ages: 1, 2, 3, 4
Working with the Low-Level API
e low-level API for MIDlets is composed of the Canvas and Graphics classes (we will discuss the
meCanvas class in the next article). The Canvas class is abstract; you must create your own canvases to
ite/draw on by extending this class and providing an implementation for the paint(Graphics g) metho
hich the actual drawing on a device is done. The Canvas and Graphics classes work together to provide
vel control over a device.
t's start with a simple canvas. Listing 7 shows an example canvas that draws a black square in the middle
e device screen.
ckage com.j2me.part2;
mport javax.microedition.lcdui.Canvas;
mport javax.microedition.midlet.MIDlet;
mport javax.microedition.lcdui.Display;
mport javax.microedition.lcdui.Graphics;
blic class CanvasExample
extends MIDlet {
Canvas myCanvas;
public CanvasExample() {
myCanvas = new MyCanvas();
}
public void startApp() {
Display display = Display.getDisplay(this);
// remember, Canvas is a Displayable so it can
// be set on the display like Screen elements
display.setCurrent(myCanvas);
// force repaint of the canvas
myCanvas.repaint();
}
public void pauseApp() {
le:///C|/Documents%20and%20Settings/akanksha/j2me/midletUI4.htm (1 of 10)7/14/2006 12:39:09 PM
http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=1http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=2http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=3http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=3http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=2http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=1http://www.java.net/ -
8/14/2019 The J2ME Big Index
44/97
ava.net: J2ME Tutorial, Part 2: User Interfaces with MIDP 2.0
}
public void destroyApp(Boolean unconditional) {
}
ass MyCanvas extends Canvas {
public void paint(Graphics g) {
// create a 20x20 black square in the center
g.setColor(0x000000); // make sure it is black
g.fillRect(
getWidth()/2 - 10,
getHeight()/2 - 10,
20, 20);
}
sting 7. Creating and displaying aCanvas
e class MyCanvas extends Canvas and overrides the paint() method. Although this method is called a
on as the canvas is made the current displayable element (by setCurrent(myCanvas)), it is a good ide
ll the repaint() method on this canvas soon afterwards. The paint() method accepts a Graphics
ject, which provides methods for drawing 2D objects on the device screen. For example, in Listing 7, a bla
uare is created in the middle of the screen using this Graphics object. Notice that before drawing the squ
ing the fillRect() method, the current color of the Graphics object is set to black by using the metho
tColor(). This is not necessary, as the default color isblack, but this illustrates how to change it if youanted to do so.
you run this listing, the output on the emulator will be as shown in Figure 8.
le:///C|/Documents%20and%20Settings/akanksha/j2me/midletUI4.htm (2 of 10)7/14/2006 12:39:09 PM
-
8/14/2019 The J2ME Big Index
45/97
ava.net: J2ME Tutorial, Part 2: User Interfaces with MIDP 2.0
gure 8. Drawing a single square in the middle of aCanvas
otice the highlighted portion at the top in Figure 8. Even though the MIDlet is running, the AMS still displaysevious screen. This is because in the paint() method, the previous screen was not cleared away, and th
uare was drawn on the existing surface. To clear the screen, you can add the following code in the paintethod, before the square is drawn.
setColor(0xffffff);
// sets the drawing color to white
fillRect(0, 0, getWidth(), getHeight());
// creates a fill rect which is the size of the screen
ote that the getWidth() and getHeight() methods return the size of the display screen as the initial
nvas, which is the whole display screen. Although the size of this canvas cannot be changed, you can cha
e size and location of the clip area in which the actual rendering operations are done. A clip area, in
aphics, is the area on which the drawing operations are conducted. The Graphics class provides the
ethod setClip(int x, int y, int width, int height) to change this clip area, which in an init
nvas is the whole screen, with the top left corner as the origin (0, 0). Thus, if you use the method
tClipWidth() (or getClipHeight()) on the Graphics object passed to the paint method in Listing 7
urns a value equal to the value returned by the getWidth() (or getHeight()) method of the Canvas.
le:///C|/Documents%20and%20Settings/akanksha/j2me/midletUI4.htm (3 of 10)7/14/2006 12:39:09 PM
-
8/14/2019 The J2ME Big Index
46/97
ava.net: J2ME Tutorial, Part 2: User Interfaces with MIDP 2.0
e Graphics object can be used to render not only squares and rectangles, but arcs, lines, characters,
ages, and text, as well. For example, to draw the text "Hello World" on top of the square in Listing 7, you cd the following code before or after the square is drawn:
drawString("Hello World", getWidth()/2, getHeight()/2 - 10,
Graphics.HCENTER | Graphics.BASELINE);
is will result in the screen shown in Figure 9.
gure 9. Drawing text using theGraphics object
xt, characters, and images are positioned using the concept of anchor points. The full syntax of theawString() method is drawstring(String text, int x, int y, int anchor). The anchor
sitioning around the x, y coordinates is specified by bitwise ORing of two constants. One constant specifie
e horizontal space (LEFT, HCENTER, RIGHT) and the other specifies the vertical space (TOP, BASELINE,
TTOM). Thus, to draw the "Hello World" text on top of the square, the anchor's horizontal space needs to b
ntered around the middle of the canvas (getWidth()/2) and hence, I have used the Graphics.HCENT
nstant. Similarly, the vertical space is specified by using the BASELINE constant around the top of the squ
etHeight()/2 - 10). You can also use the special value of 0 for the anchor, which is equivalent to TOP
FT.
ages are similarly drawn and positioned on the screen. You can create off-screen images by using the sta
eateImage(int width, int height) method of the Image class. You can get a Graphics objectsociated with this image by using the getGraphics() method. This method can only be called on image
at are mutable. An image loaded from the file system, or over the network, is considered an immutable ima
d any attempt to get a Graphics object on such an image will result in an IllegalStateException a
ntime.
sing anchor points with images is similar to using them with text and characters. Images allow an additiona
nstant for the vertical space, specified by Graphics.VCENTER. Also, since there is no concept of a base
r an image, using the BASELINE constant will throw an exception if used with an image.
sting 8 shows the code snippet from the MyCanvas class paint() method that creates an off-screen imaodifies it by adding an image loaded from the file system, and draws a red line across it. Note that you will
ed the image duke.gifin the resfolder of the CanvasExample MIDlet.
draw a modified image
y {
// create an off screen image
Image offImg = Image.createImage(25, 19);
le:///C|/Documents%20and%20Settings/akanksha/j2me/midletUI4.htm (4 of 10)7/14/2006 12:39:09 PM
-
8/14/2019 The J2ME Big Index
47/97
-
8/14/2019 The J2ME Big Index
48/97
ava.net: J2ME Tutorial, Part 2: User Interfaces with MIDP 2.0
int y) methods.
e Canvas class defines constants for key codes that are guaranteed to be present in all wireless devices.
ese key codes define all of the numbers (for example, KEY_NUM0, KEY_NUM1, KEY_NUM2, and so on) and
ar (*) and pound (#) keys (KEY_STAR and KEY_POUND). This class makes it even easier to capture gamin
ents by defining some basic gaming constants. There are nine constants that are relevant to most games:
WN, LEFT, RIGHT, FIRE, GAME_A, GAME_B, GAME_C, and GAME_D. But how does a key event translate to
ming event?
y the use of the getGameAction() method. Some devices provide a navigation control for moving aroun
e screen, while some devices use the number keys 2, 4, 6, and 8. To find out which game action key was
essed, the Canvas class encapsulates this information and provides it in the form of the game actions. Allu, as a developer, need to do is to grab the key code pressed by the user in the right method, and use the
tGameAction(int keyCode) method to determine if the key pressed corresponds to a game action. A
u can guess, several key codes can correspond to one game action, but a single key code may map to, atost, a single game action.
sting 9 extends the original code from Listing 7 to add key code handling. In this listing, the square in the
ddle of the screen is moved around with the help of the navigation buttons.
ckage com.j2me.part2;
mport javax.microedition.lcdui.Canvas;
mport javax.microedition.midlet.MIDlet;
mport javax.microedition.lcdui.Display;
mport javax.microedition.lcdui.Graphics;
blic class CanvasExampleextends MIDlet {
Canvas myCanvas;
public CanvasExample() {
myCanvas = new MyCanvas();
}
public void startApp() {
Display display = Display.getDisplay(this);
// remember, Canvas is a Displayable so it can
// be set on the display like Screen elements
display.setCurrent(myCanvas);
// force repaint of the canvas
myCanvas.repaint();
}
le:///C|/Documents%20and%20Settings/akanksha/j2me/midletUI4.htm (6 of 10)7/14/2006 12:39:09 PM
-
8/14/2019 The J2ME Big Index
49/97
-
8/14/2019 The J2ME Big Index
50/97
ava.net: J2ME Tutorial, Part 2: User Interfaces with MIDP 2.0
otice that in this listing, the code to paint the square has been modified to rely upon instance variables. The
yPressed() method has been overridden and therefore, whenever the user presses a key, this method voked. The code checks if the key pressed was a game key, and based on which game key was pressed,
anges the coordinates of the square accordingly. Finally, the call to repaint() in turn calls the paint()
ethod, which moves the square on the screen as per the new coordinates.
this article, you created the UI elements and were introduced to much of the user interface APIs for MIDle
the next installment, you will learn to use the Gaming API of MIDP 2.0 present in the package javax.
croedition.lcdui.game .
kram Goyalis the author of Pro Java ME MMAPI.
elated Articles
ME Tutorial, Part 4: Multimedia and MIDP 2.0
part four of this J2ME tutorial, you will use the Mobile Media API 1.1 (MMAPI) to load and play audio and
deo on your MIDP device.
ME Tutorial, Part 3: Exploring the Game API of MIDP 2.0
part three of this J2ME tutorial, you will use the mobile gaming package to develop a simple game, which
es all of the classes of this package, as a learning tool.
ME Tutorial, Part 1: Creating MIDlets
va 2 Micro Edition (J2ME) combines a resource-constrained JVM and a set of Java APIs for developing
plications for mobile devices. Here is a step-by-step guide to creating MIDlets, testing and deploying these
Dlets, and a look at the lifecycle of a MIDlet.
ew alljava.net Articles.
howing messages 1 through 7 of 7.
q Other typos
2005-12-14 02:00:05 gvix [Reply | View]
There are some other typos in this article:
On the first page, Displayable is referred to as an interface, when it is actually an Abstract class. Figure
also shows this error.
le:///C|/Documents%20and%20Settings/akanksha/j2me/midletUI4.htm (8 of 10)7/14/2006 12:39:09 PM
http://today.java.net/pub/au/179http://today.java.net/pub/a/today/2005/09/27/j2me4.htmlhttp://today.java.net/pub/a/today/2005/07/07/j2me3.htmlhttp://today.java.net/pub/a/today/2005/02/09/j2me1.htmlhttp://today.java.net/pub/q/articleshttp://today.java.net/cs/user/create/cs_msg?x-lr=cs_msg/16795&x-lr2=a/187http://today.java.net/cs/user/view/cs_msg/16795http://today.java.net/cs/user/view/cs_msg/16795http://today.java.net/cs/user/create/cs_msg?x-lr=cs_msg/16795&x-lr2=a/187http://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=4&x-order=date#threadhttp://today.java.net/pub/a/today/2005/05/03/midletUI.html?page=4&x-maxdepth=0#threadhttp://today.java.net/cs/user/create/cs_msg?x-lr=cs_disc/2089&x-lr2=a/187&page=4http://today.java.net/pub/q/articleshttp://today.java.net/pub/a/today/2005/02/09/j2me1.htmlhttp://today.java.net/pub/a/today/2005/07/07/j2me3.htmlhttp://today.java.net/pub/a/today/2005/09/27/j2me4.htmlhttp://today.java.net/pub/au/179 -
8/14/2019 The J2ME Big Index
51/97
-
8/14/2019 The J2ME Big Index
52/97
ava.net: J2ME Tutorial, Part 2: User Interfaces with MIDP 2.0
// put some space between the items to segregate
spacer = new Spacer(20, 20);
this.append(spacer);
// create some commands and add them
// to this form
this.addCommand(
new Command("EXIT", Command.EXIT, 1));/* form.addCommand(
new Command("HELP", Command.HELP, 2));*/
this.addCommand(
new Command("OK", Command.OK, 1));
// set itself as the command listenerthis.setCommandListener(this);
}
// handle commands
public void commandAction(Command com, Displayable dis) {
String label = com.getLabel();
if("EXIT".equals(label)) displayExit(); // midlet.SetCurrent(new);
else if("HELP".equals(label))
displayHelp();
else if("OK".equals(label))processForm();
}
public void displayHelp() {
// show help
}
public void processForm() {
// process Form}
public void displayExit() {
// show help}
}
q
le:///C|/Documents%20and%20Settings/akanksha/j2me/midletUI4.htm (10 of 10)7/14/2006 12:39:09 PM
-
8/14/2019 The J2ME Big Index
53/97
ava.net: J2ME Tutorial, Part 3: Exploring the Game API of MIDP 2.0
J2ME Tutorial, Part 3: Exploring the Game API of MIDPby Vikram Goyal
07/07/2005
ME is a popular platform for developing games for wireless devices. With MIDP 2.0, a new package has b
roduced that provides several gaming constructs that would only have been possible in MIDP 1.0 with a g
al of repetitive code. In this part of this tutorial series, I will introduce you to this gaming package and help
velop a simple game that uses all of the classes of this package as a learning tool. The package is called
vax.microedition.lcdui.game , and it builds upon the concepts that you learned in the previous
stallments in this series.
2ME Gaming API: An Overview
ere are only five classes in the javax.microedition.lcdui.game package: GameCanvas, Layer,
rite, TiledLayer, and LayerManager. These five classes are enough to provide a platform for thevelopment of games with a wide range of capabilities.
e Layer class is the superclass of the Sprite and TiledLayer classes. This class abstracts the behav
a visual element in a game. This element can be a sprite, which represents an independent graphic (or a
llection of graphics for animation) that can be moved around the game screen, or a tiled layer, whichpresents a graphic that can be used to create vast game backgrounds with only a handful of images. You
e Layer classes for positioning and visibility. The subclasses override the paint(Graphics g) method
hich has the task of rendering the elements on the screen.
e LayerManager class provides a convenient mechanism to manage the various visual elements of a ga
prites and tiled layers) by rendering the proper layer in the proper order.
e GameCanvas class is made useful by extending the functionality of the Canvas class (from the previous
icle). It provides an off-screen buffer, to which all rendering operations are done before flushing them on t
vice screen. It also provides an easy-to-use mechanism to query the current keys being pressed by the us
e best way to introduce you to these classes is with the help of a working game example, which we will bu
m the ground up, explaining the various facets of a game. This is helpful whether or not you have
ogrammed a game before, if you are looking to learn how to do it for the wireless devices using J2ME'sming API. After a quick introduction to game building (for those who have never created a game), the
maining sections introduce each of the classes from the javax.microedition.lcdui.game package,
e help of a concise but complete game.
le:///C|/Documents%20and%20Settings/akanksha/j2me/j2me31.htm (1 of 3)7/14/2006 12:39:10 PM
http://today.java.net/pub/au/179http://today.java.net/pub/a/today/2005/05/03/midletUI.htmlhttp://today.java.net/pub/a/today/2005/05/03/midletUI.htmlhttp://today.java.net/pub/a/today/2005/05/03/midletUI.htmlhttp://today.java.net/pub/a/today/2005/05/03/midletUI.htmlhttp://today.java.net/pub/au/179http://www.java.net/ -
8/14/2019 The J2ME Big Index
54/97
ava.net: J2ME Tutorial, Part 3: Exploring the Game API of MIDP 2.0
Very Short Primer on Game Building
game or animation is built according to the principle of repetitively executing a piece of code. This piece of
de tracks the value of instance variables and updates the game state accordingly. Based on the game stae code then draws/paints/repaints the game screen with the elements that make up the game. The values
e instance variables may