Developers

Local Navigation

Home > Developers > Developers Knowledge Base

Back

How To - Change the text color of a field

Last Updated: 18 April 2006
Article Number: DB-00114

Summary

This article applies to the following:

  • BlackBerry® Java™ Development Environment (JDE)
  • BlackBerry wireless devices based on Java

Procedure

You can change the color of text in a field for applications that are designed to run on a color BlackBerry device. When you define a field, you can choose a color that will not change during the life of the field. To allow a field's color to change dynamically, extend one of the existing fields, or create your own field.

Below are samples that utilize the RichTextField and change the color of the text in the field. The color in Example 1 below will stay the same for the life of the field. The code in Example 2 below allows the color to be programmatically set, or set to a random value.

Example 1

//RichTextField that displays text in the specified color.
RichTextField fontText = new RichTextField("This text will be green.")
{
    public void paint(Graphics graphics)
    {
        graphics.setColor(0x00008800);
        super.paint(graphics);
    }
};

Example 2

/**
 * Custom Field - FontField
 *
 */

import net.rim.device.api.ui.*;
import net.rim.device.api.system.*;
import net.rim.device.api.ui.component.*;
import java.util.*;

public class FontField extends RichTextField
{
    //Set the initial text color to black.
    private int color = 0x00000000;

    //Initialize the random number generator.
    private Random randColor = new Random();

    //Only one RichTextField contstructor in this sample for brevity.
    public FontField(String text)
    {
        super(text);
    }

    //Set the color of the text in this field.
    public void setColor(int newColor)
    {
        color = newColor;
    }

    //Get the current text color.
    public int getColor()
    {
        return color;
    }

    //Randomly generate a new text color.
    public void randomizeColor()
    {
        int r = Math.abs(randColor.nextInt()) % 255;
        int g = Math.abs(randColor.nextInt()) % 255;
        int b = Math.abs(randColor.nextInt()) % 255;

        color = (255<<24) | (r<<16) | (g<<8) | b;
    }

    //Set the foreground and then call paint method of the parent class.
    public void paint(Graphics graphics)
    {
        graphics.setColor(color);
        super.paint(graphics);
    }

}


Keywords

change, color, field, text