DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 8.18 Formatting a Portion of a Text Field

8.18.1 Problem

You want to add formatting to some, but not all, text in a text field, or you want to apply different formatting to various parts of a text field.

8.18.2 Solution

Create a TextFormat object and use it to format a substring of the text field using one of the setTextFormat( ) method variations.

8.18.3 Discussion

You can format an entire text field as shown in Recipe 8.16, or you can use one of the versions of the setTextFormat( ) method to format just a portion of a text field. These variations allow you to apply formatting to the specified character range only.

You can set the formatting for a single character within a text field by invoking the setTextFormat( ) method and passing it two parameters:

index

The zero-relative index of the character to which the formatting should be applied

textFormatObj

A reference to a TextFormat object

This example applies the formatting to the first character only:

myTextField.setTextFormat(0, myTextFormat);

Alternatively, if you want to apply the formatting to a range of characters, you can invoke setTextFormat( ) with three parameters:

startIndex

The beginning, zero-relative character index

endIndex

The index of the character after the last character in the desired range

textFormatObj

A reference to a TextFormat object

This example applies the formatting to the 1st through 10th characters:

myTextField.setTextFormat(0, 10, myTextFormat);

You may notice that certain formatting options are not applied under certain circumstances when you try to format portions of a text field. For example, the text alignment will be applied only if the formatting is applied to the first character in a line.

8.18.4 See Also

Recipe 8.16

    [ Team LiB ] Previous Section Next Section