Recipe 9.15.
Formatting a Portion of Existing Text
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.
Solution
Create a TextFormat object and use it to
format a substring of the text field by using one of the
setTextFormat( )
method variations.
Discussion
You can format an entire text field as shown in
Recipe
9.13, 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.
textFormat
-
A reference to a TextFormat object.
This example applies the formatting to the first
character only:
field.setTextFormat(0, formatter);
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.
textFormat
-
A reference to a TextFormat object.
This example applies the formatting to the first
10 characters:
field.setTextFormat(0, 10, formatter);
You may notice that when you try to format
portions of a text field, certain formatting options do not get
applied under certain circumstances. For example, text alignment is
applied only if the formatti
ng is applied to the first
character in the line.
See Also
Recipe
9.13
|