7.1. Using the TextLayout Class

The drawString() methods render simple pieces of text. If you're interested in support for a caret (cursor) and highlighting, you'll need to use the java.awt.font.TextLayout class. This class can be used as the basis for a sophisticated text editor. Most applications don't need the power of this customization and can simply use JTextField, JTextArea, or JEditorPane.

TextLayout offers the following features:

  • text metrics

  • hit testing

  • caret support

  • highlighting support

  • paragraph layout on multiple lines (with the help of the LineBreakMeasurer class)

7.1.1. TextLayout Basics

Creating a TextLayout is pretty simple. You just need to supply the text itself, either as a string or a character iterator, and a FontRenderContext (which was described in Chapter 6):

public TextLayout(String string, Font font, FontRenderContext frc)

Use this constructor to create a TextLayout using the supplied string and font.

public TextLayout(String string, Map attributes, FontRenderContext frc)

This constructor creates a new TextLayout from the given string. The supplied attributes are applied to the entire string. (For a list of possible attributes, see Table 6-1.)

public TextLayout(AttributedCharacterIterator text, FontRenderContext frc)

This constructor creates a TextLayout from the supplied iterator.

Once you've created a TextLayout, you can render it by calling its draw() method. This is a little different from the usual model. Usually you create something, like a shape ...

Get Java 2D Graphics now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.