O'Reilly logo

Java 2D Graphics by Jonathan Knudsen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required