Creating a BlackBerry custom field – Tutorial

Posted by

Introduction

This tutorial will show you how to create a very simple custom field (component) using the RIM API. If you’re familiar with Swing, then this code will not be a surprise to you. There are some similarities between AWT/Swing and RIM UI API.

Example

I’m going to create a custom label field that is different from the LabelField in that you can set a foreground color on it. Here’s the code to do this.

public class MyLabelField extends LabelField {

  private String text;
  private int fgColor;
  
  public MyLabelField(String text, int fgColor){
    this.text = text;
    this.fgColor = fgColor;
  }

  // @Override
  protected void layout(int w, int h){
    setExtent(w, Font.getDefault().getHeight());
  }

  // @Override
  protected void paint(Graphics g){
    g.setColor(fgColor);
    g.drawText(text, 0, 0);
  }

}

This is what’s going on in the code:

  1. The constructor of MyLabelField simply accepts a label text and foreground color. Note that this class extends LabelField.
  2. The paint() method has been overridden (just like in AWT or Swing) to provide custom painting code for this class. Here I just set the foreground color and write the string out with it.
  3. The layout() method has been overridden. You have to do something similar in Swing/AWT but the syntax here is totally different. The layout method is called by a layout manager to size and position this field on the screen. So all this method does is it returns its preferred dimensions, by calling setExtent(). The layout() method is called first, before getExtent(), by a layout manager, so it’s important that you set the extent in this method.

Feedback and comments

To share your thoughts on this tutorial click here.