J2ME StopWatch UI improvements

At Mindseye they gave us every other Friday off during the summer, so naturally I spent the time programming (it rained today in Boston, couldn’t go outside). I did get some feedback from people who installed and/or used the StopWatch app that I released last week. One of the obvious things was allowing the user to start and stop the stopwatch using what is commonly called the “FIRE” button on a phone. Turns out this is relatively easy to do because I was using the Canvas class to paint the screen. The Canvas class is (according to the documentation) “… a base class for writing applications that need to handle low-level events and to issue graphics calls for drawing to the display.” Low level events include things like key press events, pointer events, and game actions. Anyway, long story short, I added the following code to the StopWatchCanvas class constructor:

fireKey = getKeyCode( FIRE );

and this method:

protected void keyPressed( int keyCode ){
  if( keyCode == fireKey ){
    if (thread.isPaused()) {
      // get the thread out of paused mode
      thread.startWatch();
    } else {
      thread.pauseWatch();
    }
  }
}

The first line uses the getKeyCode(int gameAction) method of the Canvas class to retrieve the int value of the gameAction, which in this case is the static variable “FIRE“, also part of the Canvas class.

The keyPressed() method then listens for any and all key pressed events and calls the appropriate method in my thread class to start or stop the watch depending on what state the watch is currently in.

Couple interesting observations about this:


a) if I used one of the high level UI components to paint characters to the screen (like the Screen, Form, Item, etc. classes), I wouldn’t have been able to listen for key events (let me know if I’m wrong about that J2ME experts), so it was easy to do only because I was extending the Canvas class.

b) the options menu that is built by using Command objects still works ok. This is important because users who don’t have a “FIRE” button on their phone can still use the application.

The other UI improvement was that I added a custom icon for the stopwatch application. Didn’t find alot of documentation about this, but from what I can tell, the image that you specify in the MIDlet-Icon attribute of your jad file, must be a 24 bit 32×32 png file. Anything other than that didn’t show up on my 3650 (although it did in the emulator). The screenshots you’re seeing in this post show the icon.

The most helpful article I’ve read about the low-level MIDP api’s is “Using the MIDP Low-Level User Interface API” by Eric Giguere on wireless.java.sun.com. Take a peek if you haven’t already.

Download version 1.1 of J2ME StopWatch now!