Implementing the Login and Clear Menu Items

We'll implement two menu items for our application corresponding to the Login and Clear actions.

We'll create a new class for each menu item and declare these as inner classes within UiFunMainScreen—because we'll only use them here and to give them access to UiFunMainScreen's private login and clearTextFields methods:

public class UiFunMainScreen extends MainScreen implements FieldChangeListener { class LoginMenuItem extends MenuItem { public LoginMenuItem() { super("Login", 20, 10);

class ClearMenuItem extends MenuItem { public ClearMenuItem() { super("Clear", 10, 20);

public void run() { clearTextFields();

Notice how we arranged the ordinal and priorities with the menu items. ClearMenuItem has a lower ordinal value and higher priority value than LoginMenuItem. Therefore, Clear will appear above Login on the menu, but Login will be highlighted by default. This arrangement lets us mirror the order of the buttons on screen, but make the most likely user choice the default one, saving our users a bit of time.

There are a couple of places we can add menu items. One is in the screen's constructor, by calling getMenu and adding items to the Menu object we get back. The other is by overriding makeMenu in our screen class. We'll do the latter, because makeMenu is useful when creating context sensitive menus (menus whose items may change depending on the state of the screen). The makeMenu method in UiFunMainScreen should look like this:

protected void makeMenu(Menu menu, int instance) { super.makeMenu(menu, instance); menu.add(new LoginMenuItem()); menu.add(new ClearMenuItem());

It's very important to have the super.makeMenu call here; otherwise, the default menu items for the screen will not be added. Specifically, we'd lose the Close item that MainScreen automatically adds for us. There are times where we might want to change that, but not for this application, so we'll be sure to make the super.makeMenu call.

One final tip—we declared the menu items explicitly as classes in this example to present things in a clear order, but you'll usually see menu items declared as anonymous inner classes instead. Using an anonymous inner class is more succinct, and you generally use each menu item class only once in a given application. So instead of using the preceding implementation, we could have omitted the declarations for LoginMenuItem and ClearMenuItem and instead done the following in makeMenu:

protected void makeMenu(Menu menu, int instance) { super.makeMenu(menu, instance); menu.add(new MenuItem("Login", 20, 10) { public void run() { login();

menu.add(new MenuItem("Clear", 10, 20) { public void run() { clearTextFields();

In fact, we'll be using this form throughout the rest of this book.

0 0

Post a comment

  • Receive news updates via email from this site