Working with Lightweight User Interface Toolkit (LWUIT) 1.4

by Vikram Goyal

LWUIT is a user interface library designed to bring uniformity and cross mobile interface functionality to applications developed using Java Platform, Micro Edition (Java ME). To make applications designed using Java ME look consistent across different platforms is a big task, and LWUIT lives up to that challenge with a clean interface and a plethora of UI goodies.

Version 1.4 of this library provides support for XHTML, multi-line text fields, and customization to the virtual keyboard. This article introduces these enhancements.

What is LWUIT?

With a small footprint (541 KB jar file and less obfuscated), LWUIT is a preferred method for adding cross mobile UI features and functionality to applications developed for mass-market devices. Inspired by Swing, this library helps developers concentrate on getting business functionality correct, instead of worrying about UI fragmentation across devices.

At the same time, it provides mechanisms to make applications look consistent, and it has a rich feature set built from scratch that has no other direct dependency. It requires only MIDP 2.0 and CLDC 1.1 support on the underlying device, a requirement that is fulfilled by almost all Java ME based devices. Further, its plug and play architecture makes it easy to create UI elements that are not already provided, so it is highly customizable.

For a good introductory tutorial on LWUIT, refer to The Lightweight User Interface Toolkit (LWUIT): An Introduction.

New Features of Version 1.4

Version 1.4 is described mostly as a stability and bug fix release, but a few major features have been added as well. These major features are described in more detail below.

Version 1.4 officially supports BlackBerry, and developing an LWUIT application for a BlackBerry device has never been easier.

XHTML Support

Perhaps the most important feature of this release is the ability for LWUIT to support XHTML. Specifically, it now supports XHTML MP (Mobile Platform) 1.0, a version of XHTML designed for mobile phones. To be even more specific, it now supports CSS styling for the HTMLComponent within the LWUIT library through Wireless Application Protocol CSS (WCSS). (See the WAP CSS Specification for more information.) Since XHTML MP does not support JavaScript or frames, these are also not supported with this release.

With CSS support, the following properties are fully supported:

  • Background: background-color, background-image, background-repeat, background-attachment, background-position-x, background-position-y
  • Border: border-*-width, border-*-style, border-*-color
  • Fonts: font-family, font-size, font-style, font-weight, font-variant
  • Lists: list-style-image, list-style-position, list-style-type
  • Margins: margin-*, padding-*
  • Text: text-align, text-indent, text-transform
  • Misc: color, height, width, visibility
  • WAP: -wap-access-key, -wap-input-format, -wap-input-required

In addition, all shorthand properties are fully supported.

The following properties are only partially supported:

  • display: none and marquee are supported; block, inline, and list-item are unsupported.
  • white-space: normal and nowrap are supported; pre is unsupported.
  • vertical-align: This property works only within tables.

CSS properties that are not supported at all are clear and float.

If you don't want the system's processing and memory to be taken up by the relatively higher processing power required to render documents with CSS, you can turn CSS support off by setting the setIgnoreCSS method of the HTMLComponent class to false.

The HTMLComponent Class

The HTMLComponent class provides a very simple way to add rich text based on the XHTML-MP 1.0 specification. Initialize it with DocumentRequestHandler and use the setBodyText(String htmltext) method to render the text, which contains HTML tags. The text should not contain the <html> and <body> tags, because these are added by this method to wrap the text. You can use the setBodyText(String htmltext, String encoding) method for specific encodings. Also, if you have a full HTML document, you can use setHTML instead of the setBodyText method.

For example, the following obeys the bold and italic tags to display the message within an HTMLComponent:

  HTMLComponent h = new HTMLComponent(null);
  h.setBodyText("Hello <i>World!</i>. <b>LWUIT</b> is so cool!");
  

As you may notice, we used null to specify the DocumentRequestHandler when creating HTMLComponent. We need to use this handler only when our text is likely to contain a request for external resources in the form of links, images, and CSS files. This would be the case when you are trying to render external sites rather than HTML text that you have created yourself within the application.

To use DocumentRequestHandler, create an implementation of this interface and implement the InputStream resourceRequested(DocumentInfo docInfo) method. This method then needs to provide information to the HTMLComponent class on how to handle the expected external images, CSS, and other files. Since handling these elements would be a common task, and you shouldn't be burdened with creating a handler each time you want to display an external Web page, you would expect there to be a default implementation of this interface. Unfortunately, although there is a default implementation, it is not bundled with the LWUIT library; however, it is provided as an example in the LWUITBrowser sample code. This implementation is called HttpRequestHandler and can be accessed and imported in your code from the LWUITBrowser sample application in the LWUIT 1.4 download bundle.

Once set up, the implemented interface can be used to display any external Web page, as shown in the following code:

    HttpRequestHandler handler = new HttpRequestHandler();
    HTMLComponent h = new HTMLComponent(handler);
    h.setPage("http://m.google.com");
  

Notice that we use the setPage method of the HTMLComponent class to display the page. This method uses the HttpRequestHandler to figure out how to display the items it encounters within the page.

Multi-Line Text Fields

Since LWUIT version 1.3, several users requested that LWUIT 1.4 support a multi-line text field. The issue is complex and requires an understanding of how the TextArea and TextField classes operate and complement each other.

TextArea is implemented natively, while TextField is completely implemented within LWUIT. By being native, TextArea is portable across multiple devices, but being native also means that editing of text within a TextArea requires a different screen. This doesn't allow control over what is entered, from an LWUIT developer's point of view.

By default, TextArea supports multi-line input because it is natively implemented. With the 1.4 release, TextField supports this as well. To use it, all you need to do is override the setSingleLineTextArea method to false, because TextField extends the TextArea class. Other details on how to use TextField have not changed.

Virtual Keyboard Enhancements

If you have seen an iPhone (and other touch-screen phones) in action, you have seen the virtual keyboard that pops up when you need to enter text in an input field. LWUIT supports virtual keyboards as a pure LWUIT component, without needing to rely on native platform support. With the 1.4 release, there are several enhancements added to this component.

VirtualKeyboard Binding

VirtualKeyboard can now be bound to a text field with special restrictions. For example, if you want a text field to accept only numbers, you can do so now by creating a virtual keyboard with the NUMBERS_MODE restriction, as shown below:

   TextField tf = new TextField();
   tf.setConstraint(TextField.NUMERIC);
   tf.setInputModeOrder(new String[]{"123"});

   VirtualKeyboard vkb = new VirtualKeyboard();
   vkb.setInputModeOrder(new String[]{VirtualKeyboard.NUMBERS_MODE});
   VirtualKeyboard.bindVirtualKeyboard(tf, vkb);
 

 

VirtualKeyboard Styling

Since VirtualKeyboard is implemented in LWUIT components (that is, there is full control over what the keyboard looks like), you can now customize every aspect of a virtual keyboard, because every component in LWUIT has a style associated with it. These styles can be created using Theme Creator (formerly called Resource Editor) to design the look and feel of components within LWUIT. (See the discussion in The Lightweight User Interface Toolkit (LWUIT): An Introduction, by Jonathan Knudsen, for the basics of creating styles and themes).

Release 1.4 of LWUIT defines five new UI IDs to use within a resource file:

  • Use VKB to style the VirtualKeyboard body.
  • Use VKBtooltip to style pop-up tips.
  • Use VKBButton to style regular buttons.
  • Use VKBSpecialButton to style special buttons, such as "Shift."
  • Use VKBTextInput to style the text field that appears on the virtual keyboard itself.

Support for New Languages via Unicode

LWUIT now supports the addition of languages other than English by using Unicode to create any input language. Before this functionality can be used, VirtualKeyboard must first be initialized by calling the VKBImplementationFactory.init() method. This must be done even before calling Display.init(this).

To initiate this default keyboard with a keyboard in another language, call the VKBImplementationFactory.init(newClass) method by passing in the new class, for example:

    // first create an array of String arrays, specifying the Unicode characters for each button on the desired keyboard:
    private static final String[][] DEFAULT_JAPANESE = new String[][] {
      {"\u3042", ......}, // each array represents a column on the virtual keyboard
      {"\u30A4", ......},
      {"$Mode$", "$Space$", "$OK$"} // special buttons are usually in the last column/array
    }

    // next, you need to create a special class that extends the default VirtualKeyboard class
    public static class JapaneseK extends VirtualKeyboard {
      public JapaneseK() {
        addInputMode("SPECIAL_IDS", DEFAULT_JAPANESE); // add this to the rest of the modes
        setInputModeOrder(new String[]{"SPECIAL_IDS", QWERTY_MODE, NUMBERS_SYMBOLS_MODE, NUMBERS_MODE, SYMBOLS_MODE}); // and the order for the DEFAULT_JAPANESE
      }
    }

    // finally, just make sure that this new class is part of the initialization of the VirtualKeyboard
    VKBImplementationFactory.init(JapaneseK.class);
  

Creating Your Own Special Buttons

By default, VirtualKeyboard understands only the Shift, Delete, T9, Mode, Space, and OK special buttons. However, since we figured out how to create a virtual keyboard in the previous section, adding special buttons is not too difficult. A special button is identified by enclosing it inside a pair of $ symbols. Thus, in the previous example, $Mode$, $Space$, and $OK$ identified buttons that are handled specially. In LWUIT version 1.4, you can define your own special buttons that have their own special action handling functions.

As before, you need to extend the VirtualKeyboard class and add your special button while defining the QWERTY keyboard:

    String[][] SPECIAL_QWERTY = new String[][]{
    {"q", "w", "e", "r", "t", "y", "u", "i", "o", "p"}, ....... // and so on

    ....

    {"$Mode$", "$Space$", "$SPECIAL$"} };
 

Simple enough? We still need to add the actionPerformed method to handle what happens when the user clicks the button, and we need to reset the input mode and order:

    VirtualKeyboard vkb = new VirtualKeyboard();
    vkb.addInputMode("QWERTY_SPECIAL", SPECIAL_QWERTY);
    vkb.setInputModeOrder(new String[]{"QWERTY_SPEICAL"});
    vkb.addSpecialButton("SPECIAL", new Command("SPECIAL") {
      public void actionPerformed(ActionEvent evt) {
        // special button handling logic here
    ...
    }
    });
  

That is all that is required to add a new special button to your keyboard.

Conclusion

LWUIT is a user interface library designed to make applications that are designed using Java ME look consistent across mobile devices. This article introduced enhancements in LWUIT version 1.4, such as support for XHTML, multi-line text fields, and customization to the virtual keyboard.

See Also

About the Author

Vikram Goyal is the author of Pro Java ME MMAPI: Mobile Media API for Java Micro Edition, published by Apress. This book explains how to add multimedia capabilities to Java technology-enabled phones. Vikram is also the author of the Jakarta Commons Online Bookshelf, and he helps manage a free craft projects Web site.

Rate This Article
 
 
Comments
Terms of Use