| More
Customized Java ME LWUIT Components
 


Customized Java ME LWUIT Components

by Jim White (Intertech Director of Training and Instructor)

Several months ago, I wrote an article for DevX that introduced Java ME developers to an exciting new GUI library called LWUIT (lightweight UI toolkit) for creating richer and more portable user interfaces for Java ME applications (see http://www.devx.com/wireless/Article/38461). I still get emails because of that article. Evidence, I think, of LWUIT?s growing popularity in the Java ME community.

Most of the emails I receive want to know how to adopt and extend the framework. In fact, one of LWUIT?s strengths is that, like Java Swing from whose design inspired LWUIT, you can extend many of the LWUIT classes to add your own functionality.

Take for example an email I received from a Java ME in Bangalore, India this week. He wanted to know how to create a text field widget that only accepts characters. LWUIT?s TextField class (com.sun.lwuit.TextField) and TextArea class (com.sun.lwuit.TextArea) from which it descends allows the developer to constrain user entry to numerics, decimals, email addresses, URLs, and even phone numbers (see LWUIT API at https://lwuit.dev.java.net/nonav/javadocs/index.html). However this widget does not innately allow input to be constrained to characters (A-Z, a-z) only!

On solution is to further extend TextField (or TextArea) further. In your new TextField class, override the setText method to accept only characters. Overriding insertChar(String c) would also allow you to check characters entered directly in the widget, but you may to also check characters entered, for example, by qwerty mode.

package com.intertech.lwuit;

import com.sun.lwuit.TextField;

public class MyTextField extends TextField {
   public void setText(String text){
       super.setText(alphaOnly(text));
   }

   private String alphaOnly(String text){
       StringBuffer charOnlyText = new StringBuffer();
       for(int i = 0; i < text.length(); i++){
           char c = text.charAt(i);
           int c_i = c;
           if (( c_i >= 65 && c_i <= 90) || ( c_i >= 97 && c_i <= 122 )) {
               charOnlyText.append(c);
           }
       }
       return charOnlyText.toString();
   }
}

Any good framework helps provide the tools for tackling the most common needs. Few, if any, frameworks provide for your every need. A good framework like LWUIT also provides you an API that can be easily extended to address those needs not directly provided by the framework.

Come learn more about Java and the various API?s and open source frameworks with training classes at www.intertech.com.


Posted by: Jim White
Posted on: 2/11/2010 at 12:37 PM
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

Add comment




biuquote
  • Comment
  • Preview
Loading