If you have a paragraph of styled text that you
would like to fit within a specific width, you can use LineBreakMeasurer, which
allows styled text to be broken into lines that fit within a particular visual
advance. As you learned in the Displaying Graphics with Graphics2D (Last issue),
a TextLayout object represents unchangeable, styled character data, but it also
allows access to layout information. The getAscent and getDescent methods of
TextLayout return information about the font that is used to position the lines
in the component. The text is stored as an AttributedCharacterIterator so the
font and point size attributes can be stored with the text.
Example: LineBreakSample
The following applet positions a paragraph of styled text within a component,
using LineBreakMeasurer, TextLayout and AttributedCharacterIterator.
| ........... | |||
| ............ The complete code for this program is in LineBreakSample.java. The following code creates an iterator with the string vanGogh. The start and end of the iterator is retrieved and a new LineBreakMeasurer is created from the iterator. AttributedCharacterIterator paragraph = vanGogh.getIterator();
paragraphStart = paragraph.getBeginIndex();
paragraphEnd = paragraph.getEndIndex();
lineMeasurer = new LineBreakMeasurer(paragraph,
new FontRenderContext(null, false, false));
The size of the window is used to determine where the line should break and a
|