The FocusChangeListener specifies what actions should occur when a field gains, loses, or changes focus.
import net.rim.device.api.ui.*; import net.rim.device.api.ui.component.*; import net.rim.device.api.ui.container.*; class FocusListenerExample extends UiApplication { FocusListenerExample() { MainScreen mainScreen = new MainScreen(); RichTextField field1 = new RichTextField("Field 1"); RichTextField field2 = new RichTextField("Field 2"); FocusListener myFocusChangeListener = new FocusListener(); field1.setFocusListener(myFocusChangeListener); field2.setFocusListener(myFocusChangeListener); mainScreen.add(field1); mainScreen.add(field2); pushScreen(mainScreen); } public static void main(String[] args) { FocusListenerExample app = new FocusListenerExample(); app.enterEventDispatcher(); } class FocusListener implements FocusChangeListener { public void focusChanged(Field field, int eventType) { if (eventType == FOCUS_GAINED) { System.out.println(field + " focus gained."); } if (eventType == FOCUS_CHANGED) { System.out.println(field + " focus changed."); } if (eventType == FOCUS_LOST) { System.out.println(field + " focus lost."); } } } }
In order to catch focus change events we must create a class that implements the FocusChangeListener class. This class, in turn, must override the focusChanged method which has access to the field whose focus has changed as well as the event type. Event types include FOCUS_CHANGED, FOCUS_GAINGED, and FOCUS_LOST. In our example, when a focus event occurs we print the field and the event to the build output screen.From this point, all we need to do is create our fields, add our focus listener to the fields, and add our fields to the screen. In the example, this all takes place in the constructor. At this point, that code should be self explanatory.