Articles
Java Platform, Mobile Edition
Although high-end smart phones have gotten a lot of attention lately, mobile developers realize that these only represent a small fraction of the overall mobile space. By comparison, mobile phones based on the Java Micro Edition (Java ME) platform, including RIM's Blackberry, Nokia, Sony Ericsson, and many other manufacturers, represent about 2.6 billion devices or two thirds of the total installed base.
Therefore, for developers seeking broad deployment and adoption of their content, portability and cross-platform support has become increasingly important. Traditionally, the graphical user interface (GUI) aspect of applications has been a major stumbling block in this regard -- UI toolkits and interfaces are often specific to a platform and the UI-related code typically makes up the bulk of the application. As a result, delivery of cross-platform applications is hard. What is needed is a well designed, platform-independent UI toolkit that has lightweight memory and resource requirements, is highly portable, and open source.
The Lightweight User Interface Toolkit (LWUIT), released in mid-2008, has been a boon to mobile developers right from the start. LWUIT is a UI library targeted to a wide range of mobile devices, from mass market to high-end smart phones, and has now also been ported to other embedded platforms. The rich functionality and clean design of LWUIT makes developing and deploying rich and engaging cross-platform applications easier than ever. LWUIT is an open technology with its source and binary freely accessible for individual or commercial use.
LWUIT has seen widespread adoption by developers, ISVs, and other third parties. Numerous resources are devoted to LWUIT, including a developer guide, articles, tutorials, code samples, videos, a site with featured LWUIT-based applications, and last but not least, a very active developer community and associated forum.
This article provides a brief overview of LWUIT for those who are unfamiliar with the technology, along with a list of resources for further learning. The remainder of the article focuses on the latest features and enhancements of LWUIT 1.3, along with hands-on code samples.
As described above, LWUIT is a UI library that is licensed under the GPLv2 open-source license together with the Classpath Exception. This license encourages broad adoption while ensuring transparency and compatibility at the library level.
LWUIT offers advanced UI capabilities and a clean API that is inspired by Swing. With LWUIT, Java developers don't need to write device-specific code for different screen sizes, but instead can add UI components as needed to provide a consistent and compelling look and feel to their applications which works across a wide range of devices from different vendors.
Let's look at the LWUIT Demo application, which was written to showcase many of the different features of LWUIT such as theming, custom rendering, animations, buttons, transitions, and more. The three screenshots below show the identical application binary file (with no built-in device-specific knowledge) running on three entirely different Java ME platforms:
Screen shot 1: The LWUIT demo application running on the Java ME SDK 3.0 Mobile Emulator
Screen shot 2: The same application running on a mid-range Sony Ericsson G705
Screen shot 3: The same application running on a HTC Diamond with touch screen
Thanks to the LWUIT toolkit the application presents a rich and consistent user interface across devices and automatically adapts to and takes advantage of device-specific properties such as screen size, graphics capabilities, and touch screen support without any extra effort by the developer.
LWUIT is supported on MIDP 2.0/CLDC 1.1, has been ported onto CDC platforms, other mobile and embedded devices, and is the basis of the user interface layer for specifications such as Ginga-J for interactive TV (see: http://en.wikipedia.org/wiki/Ginga-J).
LWUIT is designed with modern UI requirements, programming styles, and best practices in mind. For example, LWUIT provides a clean separation between the UI development, the graphics design, and the business logic and therefore allows domain experts to work independently on their specific area of expertise.
Also, LWUIT is based on the MVC (model-view-controller) paradigm. For example, the List Component can display an unlimited number of items because it only renders what is visible, while the model has the data responsibility. You can show a very large list without worrying about memory consumption.
Rapid Development: One of LWUIT's key benefits is rapid development. Since the API is inspired by Swing, it is easy to learn and adopt. LWUIT itself was built from scratch and does not depend on AWT.
Portability: Another benefit is portability, and little, if any, device-specific code. To ensure portability, LWUIT was built using low-level common elements in MIDP 2.0. LWUIT applications look and run consistently across different devices and different Java runtimes.
Flexibility: Flexibility is yet another important aspect: Almost everything in LWUIT is customizable and extensible, so if there is a missing feature or component, you can create your own and plug it in your code.
Easy Deployment: Not only is LWUIT extremely powerful, well designed, and easy to use, it is also easy to deploy. During development, simply bundle the LWUIT library and resources with the application. The LWUIT components become an integrated part of the application deployment unit and are downloaded and deployed transparently when the user installs the application on their device (for example, via the standard MIDP OTA mechanism).
Wide Range of Platforms: LWUIT requires only MIDP 2.0 and CLDC 1.1 (or similar basic graphics capabilities on other platforms) and is being continually tested across a wide range of today's mass market devices -- from low-end phones with limited memory, small screens, and numeric keypads all the way to high-end devices with fast processors, high-resolution touch screens, and built-in keyboards.
LWUIT provides a Theme Creator tool for editing and creating themes and resources. This is a standalone application for creating and viewing background painting, objects, and other theme elements. It even features a live preview of the application that changes whenever updates are made to the theme or screen properties:
The new Java ME SDK 3.0 is the de facto standard for the creation of Java ME-based applications. It offers a comprehensive development suite with a host of features giving developers a powerful and convenient environment and set of tools to efficiently build and test applications.
Of course, the LWUIT toolkit can be used with the traditional Java ME tool chain. But getting started with LWUIT has never been easier now that the Java ME SDK 3.0 offers built-in support for LWUIT:
The LWUIT Demo application can be run and explored right from the main screen of the Java ME SDK 3.0. A new project type called LWUIT Application provides the necessary resources and project structure that allows developers to start building LWUIT-based applications in minutes.
LWUIT 1.3 was made available in December of 2009 and offers a number of new features and improvements.
LWUIT 1.3 Features and Improvements:
Beyond the official LWUIT 1.3 release, the LWUIT open-source subversion repository contains ongoing and additional improvements such as a pre-release version of the HTML component. The HTML component allows applications to easily render HTML conforming to XHTML Mobile Profile 1.0.
Let's walk through some of these new features in LWUIT 1.3 and the latest repository.
The table component in LWUIT features sophisticated functionality, such as support for a large number of rows and columns, horizontal and vertical scrolling, in-place editing, custom cell renders, and on-the-fly creation of cells that can feature animations, handle events, and more. Despite the multitude of functionality offered, creating tables is very straightforward -- thanks to a default table model.
The below sample application creates a complete table consisting of a header row and three columns, where column 1 and 2 are editable. Each editable data cell can be edited in place by clicking on it. The table automatically becomes scrollable horizontally and vertically if it is larger than the available space:
public class TableDemo extends MIDlet implements ActionListener {
public void startApp() {
Form form;
Resources res;
Display.init(this); // initialize LWUIT
// Load theme
try {
res = Resources.open("/res/businessTheme.res");
UIManager.getInstance().setThemeProps(res.getTheme(res.getThemeResourceNames()[0]));
} catch (IOException ioe) {
// error loading theme
}
// Create main form and add Exit command
form = new Form("Table Demo");
form.addCommand(new Command("Exit"));
form.setCommandListener(this);
// Create scrollable table with header and columns 1 and 2 editable
TableModel model = new DefaultTableModel(
new String[] {"Unedit.", "Editable", "Multiline"},
new Object[][] {
{"Row 1", "Data 1", "Multi-line\ndata"},
{"Row 2", "Data 2", "More multi-\nline data"},
{"Row 3", "Data 3", "Data\non\nevery\nline"},
{"Row 4", "Data 4", "Data (no span)"},
{"Row 5", "Data 5", "More data"},
{"Row 6", "Data 6", "More data"},
}) {
public boolean isCellEditable(int row, int col) {
return col != 0;
}
};
Table table = new Table(model);
table.setScrollable(true);
table.setIncludeHeader(true);
// Add table to form and show
form.addComponent(table);
form.show();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void actionPerformed(ActionEvent ae) {
// only action is from Exit command
destroyApp(true);
notifyDestroyed();
}
}
Running this code is easy by following these steps:
TableDemoproject from here: http://tinyurl.com/348jn29 and expand the zip file
TableDemoproject (the Java ME SDK 3.0 should recognize the TableDemo directory as a project)
TableDemoin the Projects pane, choose Properties and then in the Platform->Optional Packages panel select the Mobile Media API 1.1 check-box.
Touch-screen devices can take full advantage of the virtual keyboard functionality now available in LWUIT. A Virtual Keyboard that can be bound to a text field will slide up when the user clicks or touches the text field to input characters. The Virtual Keyboard supports a number of different input modes (text, symbols, numbers), different keymaps for customized keyboard layouts, special keys, and other sophisticated features.
Graphic: Screen Shot of Virtual Keyboard Demo on Startup and Screen Shot After User Clicks/Touches the Text Field ("Click for keyboard")
Using a Virtual Keyboard in an application is straightforward. This example application shows a basic LWUIT application with a title, an EXIT menu, a text field for entering text, and a label to display the text:
public class VKBDemo extends MIDlet implements ActionListener, FocusListener {
Form form;
Resources res;
TextField textField;
public void startApp() {
VKBImplementationFactory.init(); // initialize virtual keyboard
Display.init(this); // initialize LWUIT
// Load theme
try {
res = Resources.open("/res/businessTheme.res");
UIManager.getInstance().setThemeProps(res.getTheme(res.getThemeResourceNames()[0]));
} catch (IOException ioe) {
// error loading theme
}
// Create main form and add Exit command
form = new Form("Virtual Keyboard Demo");
form.addCommand(new Command("Exit"));
form.setCommandListener(this);
// Create text field with constraints
textField = new TextField("Click for keyboard");
textField.setConstraint(TextField.ANY);
textField.setInputModeOrder(new String[]{"Abc"});
textField.setFocusable(false); // only one component: prevent being focused right away
textField.addFocusListener(this);
// Create virtual keyboard and bind to text field
VirtualKeyboard vkb = new VirtualKeyboard();
vkb.setInputModeOrder(new String[] {VirtualKeyboard.QWERTY_MODE} );
VirtualKeyboard.bindVirtualKeyboard(textField, vkb);
// Add text field to form and show
form.addComponent(textField);
form.show();
textField.setFocusable(true); // after initial display, make focusable
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void actionPerformed(ActionEvent ae) {
// only action is from Exit command
destroyApp(true);
notifyDestroyed();
}
public void focusGained(Component cmp) {
// If user selects text field, clear it
if (cmp == textField) {
((TextField)cmp).clear();
}
}
public void focusLost(Component cmp) {
}
}
As with the TableDemo, you can download the VKBDemo project from http://tinyurl.com/348jn29 and run it with the Java ME SDK.
The HTML Component is not part of the official LWUIT 1.3 release but is now available as a pre-release in the LWUIT open-source repository.
Being able to display HTML content within an application (without having to call an external content handler) is useful for a number of reasons -- not so much to implement a full-blown mobile browser but to be able to render rich text locally, to dynamically display content pulled in from the network, or to embed web flows into your application -- basically, to fuse HTML concepts and content with your local Java application.
For these reasons, an HTML component has always been high on the LWUIT developer wish list and is now available in an early version. The support for the XHTML Mobile Profile 1.0 is about 90% completed, including text, fonts, lists, tables, forms, images, etc. as well as WCSS.
Here is a code snippet using the HTML component that shows how to display an HTML page, such as the mobile Twitter page:
// Creating a new instance of a request handler
HttpRequestHandler handler=new HttpRequestHandler();
// Creating the HTMLComponent instance and setting its request handler
HTMLComponent htmlC = new HTMLComponent(handler);
// Creating a form, adding the component to it and showing the form
Form form=new Form("HTML Demo");
form.addComponent(htmlC);
form.show();
// Setting the component to the required page
htmlC.setPage("http://m.twitter.com");
That's it! And since the HTML Component is just like any other LWUIT component it it fully touch-enabled, you can do transitions with it, theme it, etc.
Note:
HttpRequestHandler class is part of the LWUITBrowser project - you can get the full source code of the LWUITBrowser in the applications directory of the LWUIT subversion repository. For more information on the HTML component see Ofir Leitner's blog (http://www.nextgenmoco.com/2010/02/mobile-web-and-html-inside-javame-with.html).
LWUIT is very powerful - we have barely scratched the surface. Please learn more about LWUIT with the resources listed in the section below.
LWUIT developers can access a number of resources to get up to speed with LWUIT, to ask questions, and to help solve issues arising during development:
General Information on Java Micro Edition platform and tools:
LWUIT home page and overview pages:
Introductory material on LWUIT:
LWUIT blogs, YouTube channel, and application showcase:
Deep-dive technical material:
LWUIT project community forum:
Further reading: