high level display screens in j2me in stock

Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users" wishes when a user submits their information through our Contact Us form.

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

If a user"s personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user"s personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user"s account.

Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson"s commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice

To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

high level display screens in j2me in stock

Designing applications for small computing devices is a challenge, to say the least,primarily because of the limited resources found in these devices. The small computing device contains minimal memory and storage room for persistent data. Many traditional systems design methods and best practices are simply not appropriate for building applications to run on small computing devices

Asmall computing device has a radically different hardware configuration than traditional computing devices such as desktop computers and servers. Traditional computing devices are under Continuous power from the power grid, while some small computing devices such as cellular telephones rely on battery power that diminishes during the course of operation. Apower grid powers other small computing devices such as set-top boxes and appliances. Another important difference between traditional computing devices and small computing devices is the network connection

1.programs and data are stored in a small computer device’s memory, commonly referred to as primary storage. These are lost when the device drops power, although many devices have a secondary battery to retain programs and data as long as possible. 2.Once lost, programs and data must be reloaded into the device. Secondary storage is not usually available on a small computing device. 3.Therefore, a J2ME application should rely on data stored offline in a desktop computer or server rather than data stored in the device’s primary storage. 4.Data stored offline can be reloaded into the device using a network connection.

5.Don’t expect a mobile small computing device to transmit and receive data at the same rate as a device on a hard-wired network. 6.Data transmission between a mobile small computing device and a traditional computing device is slow in comparison to a hard-wired network connection because radio and infrared technology offers a narrower transmission bandwidth than that found in hard-wired network connections. 7.A bandwidth is the number of communications channels available to transmit bits of data simultaneously.

Many users of your J2ME application expect the same response from your application as they experience from desktop computer applications. Therefore, you must design your J2ME application to minimize and optimize data transmission with offline data sources. One way to optimize your J2ME application is called ROMizing the application for run-time operations. ROMizing creates a machine code image of an application before the application is deployed on the small computing device

Best Practices Over time and through trial and error, J2ME developers have come up with the best way to solve complex J2ME programming problems. And these techniques are called BEST PRACTICES AND PATTERNS. Best practices are proven design and programming techniques used to build J2ME systems. Patterns are routines that solve common programming problems that occur in such systems. Professional developers use best practices and patterns to avoid making common mistakes when designing and building a J2ME application

Typically, you design an application by dividing it into objects that have associated DATA AND METHODS. Let’s use an order form as an example. An order form is an object that has an order number, customer number, product number,and related data. Likewise, an order form has functionality associated with it, such as inserting a new order, modifying an existing order, and deleting an order. And the order form has one or more menu options that enable a user to navigate the order form.

The size of your J2ME application is critical to deploying the application efficiently. The best practice is to remove unnecessary components of your application in order to reduce the size of the overall application.

Limit the Use of Memory In addition to removing unnecessary features from your application, design your application to manage memory efficiently. There are two types of memory management that should be used in the J2ME application. These are overall memory management and peak time memory management. Overall memory management is designed to reduce the total memory requirements of an application. Peak memory management focuses on minimizing the amount of memory the application uses at times of increased memory usage on the device.

A primary way to reduce total memory requirements of your application is to avoid using object types. Instead, use scalar types, which use less memory than object types. Likewise, always use the minimum data type suited for storing data. Peak time memory management requires you to manage garbage collection. J2ME does have a garbage collector, but as with J2SE, you don’t know when the garbage collector will collect your garbage. Therefore, it is critical that you clean up after the application is finished using memory.

This reduces both memory allocation and the need for processing power. Memory allocation is reduced because multiple references can use the same object at different times in the application’s life cycle. Obviously, both objects that use the same memory cannot run simultaneously. The need for processing power is reduced because a portion of the processing required to allocate new memory doesn’t need to be invoked since memory has already been allocated when the object is instantiated.

Small computing devices are designed to run applications that do not require intensive processing because processing power common to desktop computers is not available onthese devices. This means that you must design your J2ME application to perform minimal processing on the small computing device. The alternative is to build a client-service J2ME application or web services J2ME application. There are two levels of operation in a client-service application. These are the client level and the server level. The small computing device runs the client level that provides user interface and presentation functionality to the application. The server-side level processes client requests and returns the result to the small computing device for presentation to the user. Nearly all processing occurs on the server side of the application.

2.The first layer is the client tier, sometimes referred to as the presentation tier. This is where a person interacts with an application. 3.The second layer contains the business logic that is used to fulfill requests from a client by calling appropriate software on the processing tier. 4.Processing software returns results to the business logic layer, and in turn, those results are returned to the client for presentation to the user.

Besides lightening the processing load on the small computing device, you must also be concerned about the availability of a network connection. Cellular telephone networks use technology that attempts to maintain connection as the mobile device moves from one cell to another cell. In reality there are dead zones where the mobile device is outside the range of the cellular telephone transceiver. The drop in communication can occur without warning, as many cellular telephone users have experienced.

Although you cannot avoid a break in communication, you can take steps to reduce the impact on the user of your application. Begin by keeping transmissions short—transfer the minimum information necessary to accomplish a task. Consider using store-forwarding technology and a server-side agent whenever your J2ME application requests a lot of information. A server-side agent is software running on the server that receives a request from a mobile device and then retrieves requested information from a data source, which is very similar to the business logic layer of web services technology.

Most desktop applications have a standard set of graphical user interface objects such as text boxes, combo boxes, radio buttons, check boxes, and push buttons. However, small computing devices use a variety of user display and input devices. Some devices, such as a cellular telephone, have an inch-square display and a telephone keypad for data input. There is a standard display and input for desktop computers, but you cannot say the same about small computing devices. The variety of shapes and hardware configurations found in devices classified as small computing devices makes it nearly impossible to standardize on a set of user interface objects for these devices.

It is critical that you design a user interface that takes advantage of convenient features found on a small computing device and avoid user interactions that are awkward to perform. If you decide to create a user interface containing a menu, consider the available input mechanisms of the small computer device before beginning your design. Some devices have touch screens that enable you to use icons, rather than words, to represent menu options. Other devices, such as cellular telephones, have limited keypads. Let’s say three options are presented in a list on the screen. Typically, you identify each option with a shortcut key that is a sequence of letters (A, B, C), or numbers (1, 2, 3), or a letter within the name of the option.

Use Local Variables Limited resource is the theme that echoes through design considerations for applications that run on small computing devices. As a developer, you cannot assume there are sufficient resources on every small computing device to run your application. You’ll find this line of thought radically different from the mind- set used to write applications for desktop devices and server devices, where you can safely assume that sufficient resources exist to run an application. Data storage is a key area within an application for reducing excessive processing. In many applications, developers assign values to data members of a class rather than using a local variable. You can increase processing of your application if you eliminate the extra steps of accessing a data member of a class by assigning values to local variables.

Concatenating strings is another processing drain that can be avoided by designing an application to eliminate concatenations or at least reduce the number of concatenations to the minimum necessary to achieve the objective of the application.

A string is an array of characters terminated by a NULL and stored sequentially in memory. Let’s assume the application wants to compare two strings, both of which are four characters and reside in memory. The application instructs the small computing device to copy the first character of each string into the CPU for comparison. This process continues until either the null character is reached or a letter pair is different. The entire process might require ten reading instructions and five comparison instructions, depending on when a mismatch is discovered

It is very common for developers to invoke one or multiple threads within an operation. Invoking a thread is a way of sharing a routine among other operations. For example, a sort routine can be shared simultaneously by multiple operations that must sort data. Each operation invokes the sort routine independent of other operations, although the same code is being executed for all operations.

Deadlocks and other conflicts might arise when multiple operations use the same routine. These problems are avoided by synchronizing the invocations of a thread, as you probably remember when you learned Java programming. Always use a thread whenever an operation takes longer than a tenth of a second to run because a thread requires less overhead than non-thread invocation methods, and therefore you’ll see a performance increase in your application.

A common way of reducing the overhead of starting a new thread is to create a group of thread objects that are assigned threads as needed by operations within an application. Less processing is required to assign a thread to an existing thread object than to create a new thread object. Grouping thread objects is made possible by the ThreadGroup class, but J2ME does not support this class. You can work around it, however, by creating your own grouping using the Collection class. You can store groups of thread objects in a collection and then use standard collection methods to start and stop threads in the collection and assign threads to particular thread objects within the collection.

Version management is always a concern of application developers, especially when applications are invoked from within a small computing device. You can reduce and possibly eliminate problems associated with multiple versions of the same application by requiring invocation of the application from a web server. Here’s how a small computing device can invoke a web server–based J2ME application: midp -transient Rather than running a local JAD file, the -transient option specifies that the JAD file is located on a web server identified by the URL on the command line. In this way, the developer only needs to update one copy of the application, and distribution is handled by making the latest version of the application available on the web server.

There will likely be occasions when you need to have your application perform in a certain way, depending on the type of small computing device that runs the application. First, design your application with switches that activate and/or deactivate routines depending on the value of a setting. A setting is a value assigned to a variable that is either created within the application or passed to the application as a command line parameter. J2ME applications are capable of reading the value of a setting from a JAD file and manifest file.

The J2ME program in Listing 4-2 illustrates how to read this user-defined value during run time without having to recompile or repackage the application. A user-defined value is read by invoking the getAppProperty() method and passing the name of the user-defined value to the getAppProperty() method. The getAppProperty() returns the user-defined value from either the manifest file or the JAD file depending on which of these files contains the user-defined value. Model-Version user-defined value defined in the JAD file and displays the value on the screen. Of course, you can create a compound statement that invokes the getAppProperty() method and then assigns the returned value to a variable or uses the return value directly in an expression.

MIDlet-Version: 2.0 MIDlet-Vendor: MyCompany MIDlet-Jar-URL: MIDlet-1: BestMIDlet, /images/BestMIDlet.png, Best.BestMIDlet Model-Version: M253 public class BasicMIDletShell extends MIDlet { public void startApp() System.out.println(getAppProperty("Model-Version")); } public void pauseApp() public void destroyApp( boolean unconditional)

A drop-down box is a convenient way for users to choose an item from a list of possible items, such as an abbreviation for a state. Traditionally, content of a drop-down box is loaded from the data source once when the application is invoked and remains in memory until the application terminates. While caching the contents in memory is a best practice in Java programming, caching is a questionable practice when developing a J2ME application. Loading a list of data for a drop-down box when the J2ME application is invoked is efficient if this is a short list that doesn’t require substantial memory resources. Load the list dynamically from a server whenever the list is long. Release the list once the user has made a selection, and then reload the list the next time the drop-down box is invoked. In this way, memory used to store the list can be reused between calls to the drop-down box.

Nearly every J2ME application has an interface that enables user interactions with the application. The user interface can be as simple as pressing a button on the small computing device, which causes the application to react, or as complex as displaying a form containing check boxes, radio buttons, lists, and other objects common to many applications. Selections made by a user are considered events that are forwarded to your application by the device’s application manager for processing. The application’s developer must write code that recognizes an event and then reacts to the event by performing a task based on the nature of the application.

J2ME User Interfaces 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 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. If a match occurs, the application performs the steps necessary to process the option. A developer can use one of three kinds of user interfaces for an application. These are a command, form, or canvas.

A command-based user interface consists of instances of the Command class. An instance of the Command class is a button that the user presses on the device to enact a specific task. For example, Exit is an instance of the Command class associated with an Exit button on the keypad to terminate the application. The Help button is also an instance of the Command class that is linked to the Help key on the device, which is used whenever the user requires assistance. 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, and other conventions used to display information on the screen and to collect input from the user. A form is similar to an HTML form. 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, and you interact with the display by obtaining a reference to an instance of the MIDlet’s Display class. Each MIDlet has one and only one instance of the Display class. Every J2ME MIDlet that displays anything on the screen must obtain a reference to its Display instance. This instance is used to show instances of Displayable class on the screen. The Displayable class has two subclasses. These are the 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. The Canvas class is used to display graphical images such as those used for games. Displays created using the Canvas class are considered a low-level user interface and are used whenever you need to display a customized screen.

Instances of classes derived from the Displayable class are placed on the screen by calling the setCurrent() method of the Display class. The object that is to be displayed is passed to the setCurrent() method as a parameter. It is important to note that instances of derived classes of the Item class are not directly displayable and must be contained within an instance of a Form class.  An instance of an Item class appears on the screen when the setCurrent() method is used to show the form. The getCurrent() method of the Display class is used by a MIDlet to retrieve information about the instances of derivatives of the Displayable class.

Listing 5-1 contains the JAD file for this MIDlet, and Listing 5-2 illustrates how the Display class is used to determine the color attribute of the small computing device’s screen. In this example, the MIDlet invokes the isColor() method of the Display class to determine whether the screen is capable of displaying color. If so, the MIDlet displays an instance of the TextBox class reporting that the device has a color screen; otherwise the instance reports that the device is incapable of displaying color. Of course, in a realworld MIDlet, the response returned by the isColor() method is used within the MIDlet either to activate or deactivate routines that manipulate color on the screen.

MIDlet-Version: 1.0 MIDlet-Vendor: MyCompany MIDlet-Jar-URL: CheckColor.jar MIDlet-1: CheckColor, CheckColor.png, CheckColor MicroEdition-Configuration: CLDC-1.0 MicroEdition-Profile: MIDP-1.0 MIDlet-JAR-SIZE: 100 import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class CheckColor extends MIDlet implements CommandListener private Display display; private Form form; private TextBox textbox; private Command exit; public CheckColor() { display = Display.getDisplay(this); exit = new Command("Exit", Command.SCREEN, 1); String message=null; if (display.isColor())

{ message="Color display."; } else { message="No color display"; } textbox = new TextBox("Check Colors", message, 17, 0); textbox.addCommand(exit); textbox.setCommandListener(this); } public void startApp() { display.setCurrent(textbox); public void pauseApp() public void destroyApp(boolean unconditional) { } public void commandAction(Command command, Displayable displayable) if (command == exit) destroyApp(true); notifyDestroyed(); } } }

Command Class You create an instance of the Command class by using the Command class constructor within your J2ME application. The Command class constructor requires three parameters. These are the command label, the command type, and the command priority. The Command class constructor returns an instance of the Command class. The following example illustrates a cancel command. The first parameter of the command declaration is Cancel. cancel = new Command("Cancel", Command.CANCEL, 1);

Command Listener Every J2ME application that creates an instance of the Command class must also create an instance that implements the CommandListener interface. The CommandListener is notified whenever the user interacts with a command by way of the commandAction() method. Classes that implement the CommandListener must implement the commandAction() method, which accepts two parameters. The first parameter is a reference to an instance of the Command class, and the other parameter is a reference to the instance of the Displayable class, as public void commandAction(Command command, Displayable displayable) { if (command == cancel) { destroyApp(false); notifyDestroyed(); } } The device’s application manager calls the commandAction() method and passes the command selected by the user. You must evaluate the command to determine the command selected by the user. An if statement is used in this example to evaluate the command.

2..The Back command removes the Help text box from the screen and returns the user to the original screen. 3..The last command that is found in all J2ME applications is the Exit command. 4..The Exit command terminates the application. MIDlet-Name: OnlineHelp MIDlet-Version: 1.0 MIDlet-Vendor: MyCompany MIDlet-Jar-URL: OnlineHelp.jar MIDlet-1: OnlineHelp, , OnlineHelp MicroEdition-Configuration: CLDC-1.0 MicroEdition-Profile: MIDP-1.0 MIDlet-JAR-SIZE: 100

import javax.microedition.lcdui.*; public class OnlineHelp extends MIDlet implements CommandListener { private Display display; private Command back; 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);

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 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);

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. The Item class has derivative classes that create those features. In many ways, the Item class has similarities to the Command class in that instances of both classes must be declared and then added to the form. Likewise, a listener processes instances of both the Item class and the Command class.

1..For example, your application might present options in the form of an instance of the ChoiceGroup class, which is derived from the Item class. 2..An instance of a ChoiceGroup class is a check box or radio button. The user makes a selection by choosing a check box or radio button. 3..A change in the status of an instance of the Item class is processed by the itemStateChanged() method. 4..The itemStateChanged() method is similar to the actionCommand() method used to respond to the invocation of a command by the user of your application. 5..Although these methods are similar in design, you cannot combine them into one method because the application manager specifically calls the itemStateChanged() method and actionCommand() method independently of each other.

Item Listener Each MIDlet that utilizes instances of the Item class within a form must have an itemStateChanged() method to handle state changes in these instances. public void itemStateChanged(Item item) { if (item == selection) StringItem msg = new StringItem("Your color is ", radioButtons.getString(radioButtons.getSelectedIn dex())); form.append(msg); }

MIDlet-Version: 1.0 MIDlet-Vendor: MyCompany MIDlet-Jar-URL: RadioButtons.jar MIDlet-1: RadioButtons, , RadioButtons MicroEdition-Configuration: CLDC-1.0 MicroEdition-Profile: MIDP-1.0 MIDlet-JAR-SIZE: 100 import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class RadioButtons extends MIDlet implements ItemStateListener, CommandListener { private Display display; private Form form; private Command exit; private Item selection; private ChoiceGroup radioButtons; private int defaultIndex; private int radioButtonsIndex; public RadioButtons()

{ } public void destroyApp(boolean unconditional) public void commandAction(Command command, Displayable displayable) if (command == exit) destroyApp(true); notifyDestroyed(); public void itemStateChanged(Item item) if (item == radioButtons) StringItem msg = new StringItem(Your color is ", radioButtons.getString(radioButtons.getSelectedIndex())); form.append(msg);

An instance of the ChoiceGroup class is created next. The instance has a title called “Select Your Color” and a type, which in this example is EXCLUSIVE. As you’ll learn in Chapter 6, the type of an instance of the ChoiceGroup class determines its display and functionality. The EXCLUSIVE type causes the instance to appear and function as a set of radio buttons. The MULTIPLE type transforms the instance into check boxes.

radioButtons = new ChoiceGroup( "Select Your Color", Choice.EXCLUSIVE); radioButtons.append("Red", null); radioButtons.append("White", null); radioButtons.append("Blue", null); radioButtons.append("Green", null); defaultIndex = radioButtons.append("All", null); radioButtons.setSelectedIndex(defaultIndex, true); exit = new Command("Exit", Command.EXIT, 1); form = new Form(""); radioButtonsIndex = form.append(radioButtons); form.addCommand(exit); form.setCommandListener(this); form.setItemStateListener(this); } public void startApp() { display.setCurrent(form);

Exception Handling The small computing device’s application manager oversees the operation of a MIDlet. The application manager calls the startApp(), pauseApp(), and destroyApp() methods whenever the user or the device requires a MIDlet to begin, pause, or terminate. You can regain a little control of the MIDlet’s operation by causing a MIDletStateChangeException to be thrown. MIDletStateChangeException is usedto temporarily reject a request from the application manager either to start the MIDlet (startApp()) or to destroy the MIDlet (destroyApp()). AMIDletStateChangeException cannot be thrown within the pauseApp() method.

You should incorporate routines that throw a MIDletStateChangeException whenever your MIDlet has processing that should not be interrupted by the application manager. Many developers place routines that throw a MIDletStateChangeException in the destroyApp() method since terminating a MIDlet during critical processing might have a fatal effect on communication or data.

MIDlet-Name: ThrowException MIDlet-Version: 1.0 MIDlet-Vendor: MyCompany MIDlet-Jar-URL: ThrowException.jar MIDlet-1: ThrowException, ThrowException.png, ThrowException MicroEdition-Configuration: CLDC-1.0 MicroEdition-Profile: MIDP-1.0 MIDlet-JAR-SIZE: 100 import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class ThrowException extends MIDlet implements CommandListener { private Display display; private Form form; private Command exit; private boolean isSafeToQuit; public ThrowException()

{ isSafeToQuit = false; display = Display.getDisplay(this); exit = new Command("Exit", Command.SCREEN, 1); form = new Form("Throw Exception"); form.addCommand(exit); form.setCommandListener(this); } public void startApp() display.setCurrent(form); public void pauseApp() public void destroyApp(boolean unconditional) throws MIDletStateChangeException if (unconditional == false) throw new MIDletStateChangeException();

Displayable displayable) { if (command == exit) try if (exitFlag == false) StringItem msg = new StringItem ( "Busy", "Please try again."); form.append(msg); destroyApp(false); } else destroyApp(true); notifyDestroyed(); catch (MIDletStateChangeException exception) isSafeToQuit = true; } } } }

The display is a crucial component of every J2ME application since it contains objects used to present information to the person using the application and in many cases prompts the person to enter information that is processed by the application. The J2ME Display class is the parent of Displayable, which you’ll recall from the previous chapter. The Displayable class has two subclasses of its own: Screen and Canvas. The Screen class is used to create high-level J2ME displays in which the methods of its subclasses handle details of drawing objects such as radio buttons and check boxes. In contrast, the Canvas class and its subclasses are used to create low-level J2ME displays. The methods give you pixel-level control of the display, enabling you to draw your own images and text such as those used to create games.

Screen Class You will probably spend most of your time using the Screen class and its derived classes when developing a user interface for your J2ME application. These classes contain methods that generate radio buttons, check boxes, lists, and other familiar objects that users expect to find on the screen when interacting with your application. The following illustrates the Display class hierarchy, which helps you learn the inheritance structure of the Screen class. Every MIDlet has one Display object but can have many Displayable objects, which you discovered in the previous chapter. A Displayable object is any object that can be displayed on the small computing device’s screen.

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 public class Command public class Ticker public class Graphics public interface Choice public abstract class Canvas extends Displayable

The Screen class has its own set of derived classes. These are TextBox, List, Alert, Form, and Item classes. The Canvas class also has its own derived class, the Graphics class, which you’ll learn about in the next chapter. 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.

1.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

2.The Command class is used to create a Command object that can be associated with practically any class except the Alert class. 3.You created Command objects for MIDlets that you built in the previous chapter. 4.The Ticker is a variable of the Screen class that causes text to scroll on the screen like a stock exchange ticker tape. 5.The Graphics class is a base class used by derived classes to create and display custom graphical images 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. For example, an alert is an ideal way of displaying a reminder on the screen. You implement an alert by creating an instance of the Alert class in your program using the following statement. Once created, the instance is passed to the setCurrent() method of the Display object to display the alert dialog box on the screen. alert = new Alert("Failure", "Lost communication link!", null, null); display.setCurrent(alert);

The Alert constructor requires four parameters. The first parameter is the title of the dialog box, which is “Failure” in this example. The next parameter is the text of the message displayed within the dialog box. “Lost communication link!” is the text that appears when the Failure dialog box is shown on the screen. The third parameter is the image that appears within the dialog box. The previous example doesn’t use an image; therefore the third parameter is set to null. The last parameter is the AlertType. The AlertType is a predefined type of alert. None of the predefined AlertTypes is used in the previous example, and therefore a null is used as the fourth parameter

An alert dialog box is not designed to retrieve input from a user other than the selection of the OK button to close the dialog box. This means displayable objects such as ChoiceGroup and TextBox cannot be used within an alert dialog box. Likewise, you cannot insert your own Command objects as buttons. An alert dialog box reacts in one of two ways depending on the value of the default timeout for the Alert object. The alert dialog box can remain visible until the user selects the OK button, or the alert dialog box can be visible for a specified number of milliseconds. An alert dialog box is referred to as a modal dialog box if the user must select the OK button to terminate the dialog box.  Otherwise, it is considered a timed dialog box that terminates when the default timeout value is reached.

alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); You can always retrieve the current default timeout by calling the getDefaultTimeout() method of the instance of the Alert class. The getDefaultTimeout() method returns the integer value of Alert. FOREVER or the default timeout in milliseconds.

The device’s application manager determines the screen that appears when the user dismisses the alert dialog box. However, you can control what appears following the dialog box by passing reference to the next object as the second parameter to the setCurrent() method. The second parameter is reference to the displayable object that appears on the screen once the alert dialog box is closed.

The instance of the Form class contains instances of classes necessary to open a communications link with a remote computer. In this example, the instance of the Form class is titled “Communications Link.” Notice that instances of both the Alert class and the Form class are passed to the setCurrent() method. Once the user selects OK to dismiss the alert dialog box, the device’s application manager displays the instances of the Form object, enabling the user to reestablish communication with the remote computer. form = new Form("Communication Link"); alert = new Alert("Failure", "Lost communication link!", null, null); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert, form);

MIDlet-Version: 1.0 MIDlet-Vendor: MyCompany MIDlet-Jar-URL: DisplayAlert.jar MIDlet-1: DisplayAlert, , DisplayAlert MicroEdition-Configuration: CLDC-1.0 MicroEdition-Profile: MIDP-1.0 MIDlet-JAR-SIZE: 100 import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class DisplayAlert extends MIDlet implements CommandListener { private Display display; private Alert alert; private Form form; private Command exit; private boolean exitFlag; public DisplayAlert()

{ exitFlag = false; display = Display.getDisplay(this); exit = new Command("Exit", Command.SCREEN, 1); form = new Form("Throw Exception"); form.addCommand(exit); form.setCommandListener(this); } public void startApp() display.setCurrent(form); public void pauseApp() ception is thrown public void destroyApp(boolean unconditional) throws MIDletStateChangeException if (unconditional == false) throw new MIDletStateChangeException(); } }

{ if (command == exit) try if (exitFlag == false) alert = new Alert("Busy", "Please try again.", null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert, form); destroyApp(false); } else destroyApp(true); notifyDestroyed(); catch (MIDletStateChangeException exception) exitFlag = true; } } } }

Alert Sound Each AlertType has an associated sound that automatically plays whenever the alert dialog box appears on the screen. The sound, which is different for each AlertType, is used as an audio cue to indicate that an event is about to occur. Users of your MIDlet will learn to identify events by sound cue over time and will become less dependent on the visual cue presented by the alert dialog box. An audio cue can be sounded without having to display the alert dialog box. You do this by calling the playSound() method and passing it reference to the instance of the Display class, as illustrated in the following code segment. This is a modification of the if statement in Listing 6-1. The sound associated with the AlertType WARNING is heard when the playSound() method is called. if (exitFlag == false) { AlertType.WARNING.playSound(display); destroyApp(false); }

Form Class The Form class is a container for other displayable objects that appear on the screen simultaneously. Any derived class of the Item class can be placed within an instance of the Form class. For example, instances of the StringItem class can be displayed by inserting those instances within the instance of the Form class, then showing the instance of the Form class.

Small computing device screens vary in size, so you can expect that some instances within the instance of the Form class won’t fit on the screen. However, devices typically implement scrolling, which allows the user to bring instances out of view onto the screen. An instance is placed with the instance of the Form class by calling one of two methods. These are 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. private Form form; private StringItem message; form = new Form("My Form"); message = new StringItem("Welcome, ", "glad you could come."); form.append(message);

Each instance placed on a form has an index number associated with it, beginning with the value zero. You can use the index number to reference the instance within your MIDlet, for example, when you want to insert an instance onto the form. private Form form; private StringItem message1, message2; private int index1; form = new Form("My Form"); message1 = new StringItem("Welcome, ", "glad you could come."); message2 = new StringItem("Hello, ", "Mary."); index1 = form.append(message1); form.insert(index1,message2);

An alternative to using the insert() and append() methods for associating instances of the Item class with a form is to create an array of instances of the Item class and then pass the array to the constructor when the instance of the Form class is created. This is an excellent technique for initially populating the instance of the Form class. You can then use the insert() method, append() method, set() method, and delete() method to manage instances of the Item object on the form throughout the life of the MIDlet. MIDlet-Name: CreatingFormWithItems MIDlet-Version: 1.0 MIDlet-Vendor: MyCompany MIDlet-Jar-URL: CreatingFormWithItems.jar MIDlet-1: CreatingFormWithItems, , CreatingFormWithItems MicroEdition-Configuration: CLDC-1.0 MicroEdition-Profile: MIDP-1.0 MIDlet-JAR-SIZE: 100 import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class CreatingFormWithItems extends MIDlet implements CommandListener { private Display display; private Form form; private Command exit; public CreatingFormWithItems ()

exit = new Command("Exit", Command.SCREEN, 1); StringItem messages[] = new StringItem[2]; message[0] = new StringItem("Welcome, ", "glad you could come."); message[1] = new StringItem("Hello, ", "Mary."); form = new Form("Display Form with Items", messages); form.addCommand(exit); form.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 == exit) {destroyApp(true); notifyDestroyed();

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, each of which is discussed in detail later in this chapter. Some classes derived from the Item class, such as ChoiceGroup, DateField, and TextField, are used for data entry. 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 freeform text from the user of the MIDlet.

The state of an instance of a class derived from the Item class changes whenever a user enters data into the instance, such as when a check box is selected. You can capture this change by associating an ItemStateListener with an instance of a class derived from an Item class (ChoiceGroup, for example). An ItemStateListener monitors events during the life of the MIDlet and traps events that represent changes in the state of any Item class contained in a form on the screen. The class implementing the ItemStateListener interface (the MIDlet in this case) becomes the registered listener (callback) whose itemStateChanged() method is called when an item event occurs. The device’s application manager detects the event and calls the itemStateChanged() method of the MIDlet. This similar process occurs with the CommandListener when a command event occurs, except when the commandAction() method is invoked.

private Form form; private ChoiceGroup choiceGroup; …. choiceGroup = new ChoiceGroup("Pick One", Choice.EXCLUSIVE); form.append(choiceGroup); form.setItemStateListener(this); public void itemStateChanged(Item item) { if (item == choiceGroup) // do some processing }

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. You determine the format of an instance of a ChoiceGroup class by passing the ChoiceGroup class constructor a choice type.

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. Table 6-3 lists the available DateField modes. Both methods are illustrated in the following two statements: DateField datefield = new DateField("Today", DateField.DATE); DateField datefield = new DateField("Time", DateField.TIME, timeZone); Once a DateField class is instantiated, you can use DateField class methods to enter a date and time into the date field and retrieve the date and time value that has already been entered into the date field.

The setDate() method requires one parameter, which is an instance of the Date class containing the date/time value that will appear in the date field. The getDate() method is called to retrieve the date/time value of the date field. You can use the date/time value in a number of ways within your MIDlet, such as in a calculation. Besides storing and retrieving date/time values using DateField class methods, you can also replace the DateField mode and retrieve the DateField mode of an instance of a DateField class. The setInputMode() method replaces the existing DateField mode with the mode passed as a parameter to the setInputMode() method. The getInputMode() method is used to retrieve the mode of an instance of a DateField.

MIDlet-Version: 1.0 MIDlet-Vendor: MyCompany MIDlet-Jar-URL: DateToday.jar MIDlet-1: DateToday, , DateToday MicroEdition-Configuration: CLDC-1.0 MicroEdition-Profile: MIDP-1.0 MIDlet-JAR-SIZE: 100 import java.util.*; import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class DateToday extends MIDlet implements CommandListener { private Display display; private Form form; private Date today; private Command exit; private DateField datefield; public DateToday()

form = new Form("Today"s Date"); today = new Date(System.currentTimeMillis()); datefield = new DateField("", DateField.DATE_TIME); datefield.setDate(today); exit = new Command("Exit", Command.EXIT, 1); form.append(datefield); form.addCommand(exit); form.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 == exit) destroyApp(false); notifyDestroyed(); }

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. The Gauge class provides methods to display the gauge and move the indicator. The developer must build the routine into the MIDlet to move the indicator. This means that the routine must monitor the progress of the underlying process and move the indicator of the Gauge class to a position that corresponds to the status of the process.

This statement creates an interactive gauge with the caption “Like/Dislike Gauge” and a scale of zero to 100. The first parameter passed to the constructor of the Gauge class is a string containing the caption that is displayed with the gauge. The second parameter is a boolean value indicating whether or not the gauge is interactive. The third parameter is the maximum value of the gauge, and the last parameter is the gauge’s initial value. Although a gauge is set to the interactive mode, you can still change the current value of the gauge indicator by calling the setValue() method. The setValue() method requires one parameter, which is the integer representing the new value. You must write the logic in your MIDlet to calculate the new value. Many times you will want to increment or decrement the current value of the gauge by a specific amount. Therefore, you’ll need to determine the current value of the gauge by calling the getValue() method. The getValue() method returns an integer representing the gauge’s current value.

Contains the JAD file for Listing 6-12, which shows how to create a noninteractive gauge. This example simulates monitoring a process and reporting the status of the process by moving the indicator on the gauge through the range of values from zero to 100 . The monitoring begins when the user selects the Start command. The commandAction() method then loops through moving the indicator by retrieving the current value of the indicator, incrementing that value, and then repositioning the indicator on the gauge. It is within this loop that you place statements that evaluate the status of a process, which is then reflected by positioning the indicator.

TextField Class The TextField class is used to capture one line or multiple lines of text entered by the user. The number of lines of a text field depends on the maximum size of the text field when you create an instance of the TextField class. You instantiate the TextField class by using the following statement, passing the TextField constructor four parameters: textfield = new TextField("First Name:", "", 30, TextField.ANY);

The second parameter is text that you want to appear as the default text for the instance, which the user can edit. The third parameter is the maximum number of characters that can be held by the instance. You can determine the actual character size of a text box by calling the getMaxSize() method once the text field is instantiated. Always check the maximum size of a text field before populating it if your MIDlet is likely to populate the text field with a lot of text. In this way you can prevent an error from occurring during run time. You can also change the maximum size by calling the setMaxSize() method. The setMaxSize() method requires one parameter, which is the new value for the maximum size for the text field. Any time that you need to know the length of the text in the text field you can call the size() method, which returns an integer representing the number of characters existing in the text field.

Three special-purpose constraints— ADDR, PHONENUMBER, and URL— act as filters to assure that only valid characters can be entered into the text field for addresses, phone numbers, and URLs. All other characters are treated as an error and therefore are prevented from being stored in the text field. The PASSWORD constraint can be combined with other constraints to hide characters from being displayed. An asterisk or other character determined by the device is displayed in place of the actual character placed in the text box. The CONSTRAINT_MASK constraint is used to determine the constraint’s current value. There are two methods you can use to retrieve characters entered into a text field by the user of your MIDlet. --These are the getString() method and the getChars() method. The getString() method returns the content of the text field as a string, and the getChars() method returns the text field content as a character array. The getChars() method requires that you pass it a character array as a parameter.

The setString() method requires one parameter, which is the string containing text that should appear in the text field. The setChars() method requires three parameters. The first is the character array whose data will populate the text field. The second is the position of the first character within the array that will be placed into the text field. The last parameter is the length of characters of the character array that will be placed into the text field.  Characters in the character array will replace the entire content of the text field.

You can insert characters within the text field without overwriting the entire content of the text field by calling the insert() method. The insert() method has two signatures, one for strings and the other for character arrays. The insert() method used to insert a string into the contents of a text field requires two parameters. The first parameter is the string that will be inserted into the text field. The other parameter is the character position of the current string where the new text is inserted. The text that exists there now will be shifted down to make room for the inserted text. The insert() method used to insert a character array requires four parameters. The first parameter is reference to the array. The second parameter is the position of the first character within the array that will be placed into the text field.

The third parameter is the number of characters contained in the array that will be placed into the text field. And the last parameter is the character position of the current text that will be shifted down to make room for the inserted text. Text can be removed from the text field by calling the delete() method, which requires two parameters. The first is the position of the first character to be deleted. The other parameter is the length of characters that are to be deleted. The constraint of a text field can be changed after the instance is created by calling the setConstraints() method. The setConstraints() method requires you to pass the new constraint as a parameter to the setConstraints() method.  You can also determine the current constraint by calling the getConstraints() method.

Notice that an instance of a TextField class is created within the TextCapture constructor. This text field is labeled “First Name:” and can receive up to 30 characters of any kind. Initially, the text field is empty. Also notice that instances of two commands are created. One command is called Submit and is selected after the user enters a first name in the text box. The other command is the Exit command and is used to terminate the MIDlet. The form containing the text field is displayed on the screen by calling the setCurrent() method in the startApp() method . The Submit command is detected and processed by the commandAction() method, as described in the “Item Class” section of this chapter. If the command passed to the commandAction() method is the Submit command, the MIDlet calls the getString() method to retrieve the string from the text field.

If you drop down to the commandAction() method, you’ll see that the setConstraints() method is called, changing the constraint from ANY | PASSWORD to ANY, which causes characters placed in the text field to be displayed unchanged. The MIDlet also calls the setString() method to replace the hidden content of the text field with the “Thank you.” string.

MIDlet-Version: 1.0 MIDlet-Vendor: MyCompany MIDlet-Jar-URL: TextFieldCapture.jar MIDlet-1: TextFieldCapture, , TextFieldCapture MicroEdition-Configuration: CLDC-1.0 MicroEdition-Profile: MIDP-1.0 M