Introduction to the eSWT mobile extension, Part 1: Use simple widgets to quickly build mobile applications

As mobile platforms become increasingly sophisticated, the demand for mobile computing will increase. In this series, learn about the embedded Standard Widget Toolkit (eSWT). You can use eSWT to develop native-looking Java™ applications for a variety of mobile phones. This article explores how to use eSWT mobile controls. Code examples walk you through using five of the classes in the eSWT mobile extension.

Uriel Liu (liukl@tw.ibm.com), Software Engineer, IBM

Uriel LiuUriel Liu is a software developer at the IBM China Software Development Lab and works in WED client technology. He is also a committer on the eRCP project.



Eric Hsu (mfhsu@tw.ibm.com), Software Engineer, IBM

Eric HsuEric Hsu is a software developer at the IBM China Software Development Lab in Taipei. He works in Lotus Expediter client technology and Eclipse eRCP project development. He is a committer to the Eclipse eRCP project, as well.



15 September 2009

Also available in Russian Japanese Vietnamese

Introduction

As increasingly sophisticated mobile platforms proliferate, the demand for mobile computing will increase. The embedded Standard Widget Toolkit (eSWT) Mobile Extension is an Eclipse technology that can be used to develop native-looking Java applications for a variety of mobile phones.

eSWT provides standard embedded widgets to build mobile applications. It is part of the embedded Rich Client Platform (eRCP) project. eSWT is primarily concerned with meeting the functional and user experience requirements of mobile devices. eSWT provides efficient, portable access to the user-interface facilities of the devices on which it is implemented. It is a subset of the desktop SWT API. For deployment adaptability, the API is divided into two packages:

  • Core eSWT contains the base function and simple widgets.
  • Expanded eSWT contains more complex widgets (Table, Tree, WebBrowser) and additional layouts and dialogs.

This article assumes you have a fundamental understanding of eSWT and eRCP.


Overview

Table 1 provides an overview of the eSWT mobile extensions. You can also view the class hierarchy.

Table 1. Classes included in eSWT mobile extension
Control typesClass/InterfacesDescription
ControlsCaptionedControlUsed to display a label (caption) in front of a control. An optional trailing text can be used after the control.
ConstrainedTextA single-line text control that constrains the user input by styles.
DateEditorA special data-entry control that allows users to enter or choose a date.
ListBox/ListBoxItemRepresents a selectable UI object that displays a list of items consisting of text and icons from a data model. A Model-View-Control (MVC) widget in eSWT.
ListViewA widget that allows users to select one or more items from a collection of items that can be displayed in a multi-column format with different styles.
MobileShellA shell particularly suitable for devices that require dynamic change of trims at runtime. You can use it to display an application in full-screen mode.
SortedListRepresents a selectable UI object that displays a sorted list of text items. A visual filter can be used to filter the list with user input.
HyperLinkRepresents a selectable UI object that launches other applications when activated by the end user.
TextExtensionContains methods for extending the functions of the text control.
WidgetsTaskTipProvides feedback to the user about the state of a long-running task.
DialogsMultiPageDialogInstances of this class represent a tabbed dialog.
QueryDialogA modal window used to prompt the end user for data input.
TimedMessageBoxA modal window used to briefly inform the user of limited information using a standard style.
Device-relatedMobileDevice / MovileDeviceEvent / MobileDeviceListenerInstances of this class represent the device being used. It provides methods that enable applications to learn more about the device-specific characteristics and capabilities.
Screen / ScreenEvent / ScreenListenerInstances of this class represent display screens available for application use.
InputInstances of this class represent key-based input features.

The rest of this article explores the first five mobile controls. Download the sample code snippets used in this article.


CaptionedControl

You can use CaptionedControl to display a label, or caption, in front of a control. An optional trailing text can be used after the control, such as indicating units of measurement, for example.

Determining which control has focus can be difficult on mobile devices where lighting conditions are often less than optimal. Use CaptionedControl to caption a control with a label that shows focus highlighting whenever the control has focus. With an entire label highlighted, it's easy to find the focus point.

You can use the following mutually exclusive styles to define a CaptionedControl.

LEFT_TO_RIGHT
The default style. Elements inside CaptionedControl are aligned from left to right.
RIGHT_TO_LEFT
Elements inside CaptionedControl are aligned from right to left.

CaptionedControl has several getters and setters to operate on its attributes. Listing 1 shows a code sample that creates two CaptionedControls.

Listing 1. Creating two CaptionedControls
CaptionedControl captionedControl = new CaptionedControl(shell, SWT.LEFT_TO_RIGHT);
captionedControl.setText("Name: ");
Text text = new Text(captionedControl, SWT.SINGLE);
text.setText("Dr. John Wimer");
captionedControl.setTrailingText("Surgeon");
Image image1 = new Image(display,"res/surgeon.png");
captionedControl.setImage(image1);

CaptionedControl captionedControl2 = new CaptionedControl(shell, SWT.LEFT_TO_RIGHT);
captionedControl2.setText("Name: ");
Text text2 = new Text(captionedControl2, SWT.SINGLE);
text2.setText("Jessica");
captionedControl2.setTrailingText("Receptionist");
Image image2 = new Image(display,"res/receptionist.png");
captionedControl2.setImage(image2);

The code snippet above creates two text controls captioned by CaptionedControl. The example also creates two images to better describe their job titles. The code result is shown in Figure 1, with the focused control highlighted.

Figure 1. Sample CaptionedControls
Sample CaptionedControls

ConstrainedText

ConstrainedText is a single-line text control that constrains the style the user may input. This control limits the characters users can enter to make data entry more efficient. It also limits the characters than can be entered within the field.

You can use the following mutually exclusive styles to create different types of ConstrainedText.

DECIMAL
The decimal input style allows numeric values with optional decimal fractions. For example, -123, 0.123, or .5 are all valid input.
NUMERIC
The numeric input style allows numeric values.
PHONENUMBER
The phone number input style allows numeric values with optional phone-specific characters, such as +, * and #.

The code sample in Listing 2 creates different types of ConstrainedText.

Listing 2. ConstrainedText samples
Composite composite1 = new Composite(shell,SWT.NONE);		
composite1.setLayout(new RowLayout(SWT.HORIZONTAL));	
Label phoneNumber = new Label(composite1,SWT.NONE);
phoneNumber.setText("Phone Number: ");
ConstrainedText cT1 = new ConstrainedText(composite1, SWT.BORDER, 
                                          ConstrainedText.PHONENUMBER);

Composite composite2 = new Composite(shell,SWT.NONE);		
composite2.setLayout(new RowLayout(SWT.HORIZONTAL));	
Label decimal = new Label(composite2,SWT.NONE);
decimal.setText("Decimal: ");
ConstrainedText cT2 = new ConstrainedText(composite2, SWT.BORDER, 
                                          ConstrainedText.DECIMAL);

Composite composite3 = new Composite(shell,SWT.NONE);		
composite3.setLayout(new RowLayout(SWT.HORIZONTAL));	
Label numeric = new Label(composite3,SWT.NONE);
numeric.setText("Numeric: ");
ConstrainedText cT3 = new ConstrainedText(composite3, SWT.BORDER, 
                                          ConstrainedText.NUMERIC);

The code above creates three ConstrainedTexts that limit the input to only phone number, with decimal and numeric styles. The result is shown in Figure 2 with some sample input text.

Figure 2. Sample ConstrainedText
Sample ConstrainedText

DateEditor

DateEditor is a special data-entry control that lets users enter or choose a date. The return value of getDate() is an instance of a Date class.

The default locale and time zone for the date and time formatting reflects the current configuration in the device. If a date is not set, the current date is the default used. Applications may call setTimeZone(timeZone) to change the differential added to Coordinated Universal Time (UTC) time. This change only affects the widget instance and does not affect other applications.

You can use the following mutually exclusive styles to create different types of DateEditor.

DATE
A date entry type for year, month, and day.
DATE_TIME
An entry type for date and time.
DURATION
An entry type for a period of time in hours, minutes, and seconds.
OFFSET
An entry type for a period of time in hours, minutes, and seconds that can be subtracted or added to another time value.

With these styles, you can use the logical bitwise operation or with one of the widget-specific styles hints:

COMPACT
A hint that the widget should be displayed in a format that's smaller or less full-featured.
FULL
A hint that the widget should be displayed in a format that's full-featured and emphasizes ease of use, rather than compactness.

There are several getters and setters to set or get the date and time. You can also use setTimeZone() to change the application time zone. eRCP javadoc has details about usage.

Listing 3 shows sample code that creates different types of DateEditor.

Listing 3. DateEditor samples
DateEditor dateEditor1 = new DateEditor(composite, SWT.NONE, DateEditor.DATE);
DateEditor dateEditor2 = new DateEditor(composite, SWT.NONE, DateEditor.TIME);
DateEditor dateEditor3 = new DateEditor(composite, SWT.NONE, 
                                        DateEditor.DURATION);
DateEditor dateEditor4 = new DateEditor(composite, SWT.NONE, 
                                        DateEditor.OFFSET);		
dateEditor3.setTime(1000);
dateEditor4.setTime(-1000);

Four types of DateEditor are created.

Figure 3. Sample DateEditor
Sample DateEditor

The first DateEditor is a date-style control. The user can click on the anchor on the right to bring up a date/time selector.

Figure 4. DateEditor as a date/time picker
DateEditor as a date/time picker

ListBox

ListBox represents a selectable UI object that displays a list of items, such as text and icons from a data model. Each list item may include combinations of heading text, heading icons, detail text, and detail icons. You can use styles and modifiers to set the layout and display of ListBox.

Unlike List, data contained in ListBox is from a array of ListBoxItem, rather than adding or inserting one by one, to provide an MVC model. Heading and detail icons in a ListBoxItem will be displayed at the size provided, or stretched to fit the ListBox styles. To make the representation consistent, all heading icons should be the same size, and all detail icons should be the same size for any one list. Elements of a ListBoxItem that are null won't be displayed in the ListBox layout.

You can use the following mutually exclusive styles to create different types of ListBox:

LB_STYLE_NO_HEADING_TEXT
Displays single-line items with only one column (detail text). It is also the default style if the style attribute is not specified.
LB_STYLE_1LINE_ITEM
Displays single-line items with two columns (heading text and detail text).
LB_STYLE_2LINE_ITEM
Displays double-line items — one column with heading and detail combined.

The styles above can be bitwise ORed with any number of modifier styles below.

LB_MOD_SHOW_SELECTION_NUMBER
Shows a single-digit number aligned with each item, which may be used to select the item. For example, 1 means press 1 on the keypad to select this item.
LB_MOD_SHOW_HEADING_ICONS
Shows the icon associated with heading text.
LB_MOD_SHOW_DETAIL_ICONS
Shows icons associated with detail text.

Since ListBox is an MVC widget, when you change anything in the model part (ListBoxItem), you can use the following methods to keep the view part synced with the model's change.

setDataModel(ListBoxItem[] items)
Sets the data model of this ListBox. This array will be used in the lifetime of the ListBox unless you set another array as ListBox's data model.
public void refreshItem(int index)
When you make a change to one ListBoxItem, you can notify this ListBox that the data for the item at the given index has been updated and the item display needs to be refreshed.
refreshList()
When you make changes to several ListBoxItems, you can use this to refresh the entire list display in this ListBox.

The code in Listing 4 creates one array of ListBoxItem and sets it as the model for different types of ListBox.

Listing 4. ListBox samples
int[] modes={
  ListBox.LB_STYLE_2LINE_ITEM | ListBox.LB_MOD_SHOW_HEADING_ICONS |
  ListBox.LB_MOD_SHOW_DETAIL_ICONS,
  ListBox.LB_STYLE_1LINE_ITEM | ListBox.LB_MOD_SHOW_HEADING_ICONS |
  ListBox.LB_MOD_SHOW_DETAIL_ICONS,
  ListBox.LB_STYLE_1LINE_ITEM | ListBox.LB_MOD_SHOW_HEADING_ICONS |
  ListBox.LB_MOD_SHOW_DETAIL_ICONS | ListBox.LB_MOD_SHOW_SELECTION_NUMBER,
  ListBox.LB_STYLE_1LINE_ITEM | ListBox.LB_MOD_SHOW_DETAIL_ICONS |
  ListBox.LB_MOD_SHOW_SELECTION_NUMBER,
  ListBox.LB_STYLE_NO_HEADING_TEXT|ListBox.LB_MOD_SHOW_DETAIL_ICONS,
  ListBox.LB_STYLE_NO_HEADING_TEXT
  };
  
// Create the data modal
ListBoxItem[] listboxitems = new ListBoxItem[3];

// Get images
Image surdetail = new Image(display, "res/ambunance-2-24x24.png");
Image surheading = new Image(display, "res/surgeon-32x32.png");
Image nurdetail = new Image(display, "res/syringe-24x24.png");
Image nurheading = new Image(display, "res/nurse-32x32.png");
Image pragdetail = new Image(display, "res/red-cross-24x24.png");
Image pregheading = new Image(display, "res/pregnant-32x32.png");

listboxitems[0] = new ListBoxItem("Bill Marshall", surdetail, "Surgeon", surheading);
listboxitems[1] = new ListBoxItem("Nancy Moore", nurdetail, "nurse", nurheading);
listboxitems[2] = new ListBoxItem("Lily Davis", pragdetail, "Pregnant", pregheading);

// Then we call creation of ListBox several times with different 
// styles to see different visual effect
ListBox[] listbox = new ListBox[6];
for (int i=0; i<6; i++) {
  // create new Listbox
  listbox[i] = new ListBox(composite, SWT.SINGLE, modes[i] );
  // add the ListBoxItems to the ListBox
  listbox[i].setDataModel(listboxitems);
}

The result of the code snippet above is shown below.

Figure 5. Sample ListBox
Sample ListBox

ListView

ListView allows users to select one or more items from a collection of items that can be displayed in a multi-column format with different styles. It is similar to List, but also provides icon support in each item for a more fancy visual appearance.

ListView lays out its children items in one or more columns from top to bottom. If a layout-orientation hint is not specified, the implementation chooses the orientation. If there is only enough screen width for one column, the list scrolls vertically. If there is room to display multiple columns within the widget, the list scrolls horizontally. The list never scrolls in more than one direction. The layout orientation may be set at runtime by calling the setLayout(int) method.

The item-density hint determines the size and positioning of items in order to fit more or less within the widget. Applications can query the preferred sizes of the icons for each density level. The sizes may be diverse in different platforms. When the given icons do not match the preferred size, the implementation may adjust icon sizes without throwing any exception. Applications can change the item density level at runtime by calling the setLayoutDensity(int) method.

ListView has two style variables: SWT and density. With the SWT style, you can specify the selection type (single or multiple) and layout style (vertical or horizontal). For example, you can use SWT.SINGLE | SWT.VERTICAL to create a single selection, vertical layout ListView. The following are mutually exclusive styles you can use to create a ListView.

LOW
Low density
MEDIUM
Medium density
HIGH
High density

Listing 5 shows a code sample that creates a ListView containing 20 items, all of which are added with icons. It also creates two commands to demonstrate the density visual effect.

Listing 5. ListBox samples
final ListView lv = new ListView(composite, SWT.MULTI, ListView.HIGH);

//set Image array
Image[] image = new Image[4];
image[0] = new Image(Display.getDefault(), "res/pregnant-32x32.png");
image[1] = new Image(Display.getDefault(), "res/nurse-32x32.png");
image[2] = new Image(Display.getDefault(), "res/surgeon-32x32.png");
image[3] = new Image(Display.getDefault(), "res/pill-32x32.png");
lv.setSize(200,250);

//Create a Command for setting low density
Command lowCommand = new Command(lv, Command.SELECT, 0);
lowCommand.setText("LOW");
lowCommand.addSelectionListener(new SelectionListener(){
  public void widgetSelected(SelectionEvent e) {
  	lv.setLayoutDensity(ListView.LOW);
  }
  public void widgetDefaultSelected(SelectionEvent e) {
  }});

//Create a Command for setting high density
Command midCommand = new Command(lv, Command.SELECT, 0);
midCommand.setText("MEDIUM");
midCommand.addSelectionListener(new SelectionListener(){
  public void widgetSelected(SelectionEvent e) {
    lv.setLayoutDensity(ListView.MEDIUM);
  }
  public void widgetDefaultSelected(SelectionEvent e) {
}});

//add ListView items
for (int i=0; i<20; i++) {
  lv.add("item"+i, image[i % 4]);
}

The result of the code above is shown in Figure 6 with medium density and in Figure 7 with low density.

Figure 6. Medium-density ListView
Medium-density ListView
Figure 7. Low-density ListView
Low-density ListView

Conclusion

This article introduced you to the eSWT mobile extension. You also learned about five mobile controls. You can review the code samples in Download if you have questions.

Part 2 of this series explores more eSWT mobile extension classes and interfaces.


Download

DescriptionNameSize
Sample code snippetsos-eSWT_MobExt_Test_One.zip39KB

Resources

Learn

Get products and technologies

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Open source on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Open source, Java technology
ArticleID=427070
ArticleTitle=Introduction to the eSWT mobile extension, Part 1: Use simple widgets to quickly build mobile applications
publish-date=09152009