APIdia Launch Partner
Top Description Inners Fields Constructors Methods
java.awt.font

public final Class TextLayout

extends Object
implements Cloneable
Class Inheritance
All Implemented Interfaces
java.lang.Cloneable
Imports
java.awt.Color, .Font, .Graphics2D, .Rectangle, .Shape, java.awt.font.NumericShaper, .TextLine.TextLineMetrics, java.awt.geom.AffineTransform, .GeneralPath, .NoninvertibleTransformException, .Point2D, .Rectangle2D, java.text.AttributedString, .AttributedCharacterIterator, .AttributedCharacterIterator.Attribute, .CharacterIterator, java.util.Map, .HashMap, .Hashtable, sun.font.AttributeValues, .CodePointIterator, .CoreMetrics, .Decoration, .FontLineMetrics, .FontResolver, .GraphicComponent, .LayoutPathImpl

TextLayout is an immutable graphical representation of styled character data.

It provides the following capabilities:

A TextLayout object can be rendered using its draw method.

TextLayout can be constructed either directly or through the use of a LineBreakMeasurer. When constructed directly, the source text represents a single paragraph. LineBreakMeasurer allows styled text to be broken into lines that fit within a particular width. See the LineBreakMeasurer documentation for more information.

TextLayout construction logically proceeds as follows:

All graphical information returned from a TextLayout object's methods is relative to the origin of the TextLayout, which is the intersection of the TextLayout object's baseline with its left edge. Also, coordinates passed into a TextLayout object's methods are assumed to be relative to the TextLayout object's origin. Clients usually need to translate between a TextLayout object's coordinate system and the coordinate system in another object (such as a Graphics object).

TextLayout objects are constructed from styled text, but they do not retain a reference to their source text. Thus, changes in the text previously used to generate a TextLayout do not affect the TextLayout.

Three methods on a TextLayout object (getNextRightHit, getNextLeftHit, and hitTestChar) return instances of TextHitInfo. The offsets contained in these TextHitInfo objects are relative to the start of the TextLayout, not to the text used to create the TextLayout. Similarly, TextLayout methods that accept TextHitInfo instances as parameters expect the TextHitInfo object's offsets to be relative to the TextLayout, not to any underlying text storage model.

Examples:

Constructing and drawing a TextLayout and its bounding rectangle:

  Graphics2D g = ...;
  Point2D loc = ...;
  Font font = Font.getFont("Helvetica-bold-italic");
  FontRenderContext frc = g.getFontRenderContext();
  TextLayout layout = new TextLayout("This is a string", font, frc);
  layout.draw(g, (float)loc.getX(), (float)loc.getY());

  Rectangle2D bounds = layout.getBounds();
  bounds.setRect(bounds.getX()+loc.getX(),
                 bounds.getY()+loc.getY(),
                 bounds.getWidth(),
                 bounds.getHeight());
  g.draw(bounds);

Hit-testing a TextLayout (determining which character is at a particular graphical location):

  Point2D click = ...;
  TextHitInfo hit = layout.hitTestChar(
                        (float) (click.getX() - loc.getX()),
                        (float) (click.getY() - loc.getY()));

Responding to a right-arrow key press:

  int insertionIndex = ...;
  TextHitInfo next = layout.getNextRightHit(insertionIndex);
  if (next != null) {
      // translate graphics to origin of layout on screen
      g.translate(loc.getX(), loc.getY());
      Shape[] carets = layout.getCaretShapes(next.getInsertionIndex());
      g.draw(carets[0]);
      if (carets[1] != null) {
          g.draw(carets[1]);
      }
  }

Drawing a selection range corresponding to a substring in the source text. The selected area may not be visually contiguous:

  // selStart, selLimit should be relative to the layout,
  // not to the source text

  int selStart = ..., selLimit = ...;
  Color selectionColor = ...;
  Shape selection = layout.getLogicalHighlightShape(selStart, selLimit);
  // selection may consist of disjoint areas
  // graphics is assumed to be translated to origin of layout
  g.setColor(selectionColor);
  g.fill(selection);

Drawing a visually contiguous selection range. The selection range may correspond to more than one substring in the source text. The ranges of the corresponding source text substrings can be obtained with getLogicalRangesForVisualSelection():

  TextHitInfo selStart = ..., selLimit = ...;
  Shape selection = layout.getVisualHighlightShape(selStart, selLimit);
  g.setColor(selectionColor);
  g.fill(selection);
  int[] ranges = getLogicalRangesForVisualSelection(selStart, selLimit);
  // ranges[0], ranges[1] is the first selection range,
  // ranges[2], ranges[3] is the second selection range, etc.

Note

Font rotations can cause text baselines to be rotated, and multiple runs with different rotations can cause the baseline to bend or zig-zag. In order to account for this (rare) possibility, some APIs are specified to return metrics and take parameters 'in baseline-relative coordinates' (e.g. ascent, advance), and others are in 'in standard coordinates' (e.g. getBounds). Values in baseline-relative coordinates map the 'x' coordinate to the distance along the baseline, (positive x is forward along the baseline), and the 'y' coordinate to a distance along the perpendicular to the baseline at 'x' (positive y is 90 degrees clockwise from the baseline vector). Values in standard coordinates are measured along the x and y axes, with 0,0 at the origin of the TextLayout. Documentation for each relevant API indicates what values are in what coordinate system. In general, measurement-related APIs are in baseline-relative coordinates, while display-related APIs are in standard coordinates.

See Also
LineBreakMeasurer, TextAttribute, TextHitInfo, LayoutPath

Nested and Inner Type Summary

Modifier and TypeClass and Description
public static class
TextLayout.CaretPolicy

Defines a policy for determining the strong caret location.

Field Summary

Modifier and TypeField and Description
private static final float
private byte
private float[]
private Rectangle2D
private boolean
private boolean
private int
public static final TextLayout.CaretPolicy
DEFAULT_CARET_POLICY

This CaretPolicy is used when a policy is not specified by the client.

private static float
private static float
private boolean
private float
private TextLine.TextLineMetrics
private Rectangle2D
private TextLine
private float

Constructor Summary

AccessConstructor and Description
public
TextLayout(String
the text to display
string
,
Font
a Font used to style the text
font
,
FontRenderContext
contains information about a graphics device which is needed to measure the text correctly. Text measurements can vary slightly depending on the device resolution, and attributes such as antialiasing. This parameter does not specify a translation between the TextLayout and user space.
frc
)

Constructs a TextLayout from a String and a Font.

public
TextLayout(String
the text to display
string
,
Map<? extends AttributedCharacterIterator.Attribute, ?>
the attributes used to style the text
attributes
,
FontRenderContext
contains information about a graphics device which is needed to measure the text correctly. Text measurements can vary slightly depending on the device resolution, and attributes such as antialiasing. This parameter does not specify a translation between the TextLayout and user space.
frc
)

Constructs a TextLayout from a String and an attribute set.

public
TextLayout(AttributedCharacterIterator
the styled text to display
text
,
FontRenderContext
contains information about a graphics device which is needed to measure the text correctly. Text measurements can vary slightly depending on the device resolution, and attributes such as antialiasing. This parameter does not specify a translation between the TextLayout and user space.
frc
)

Constructs a TextLayout from an iterator over styled text.

pack-priv
TextLayout(TextLine
the line measurement attributes to apply to the the resulting TextLayout
textLine
,
byte
the baseline of the text
baseline
,
float[]
the baseline offsets for this TextLayout. This should already be normalized to baseline
baselineOffsets
,
float
0 if the TextLayout cannot be justified; 1 otherwise.
justifyRatio
)

Creates a TextLayout from a TextLine and some paragraph data.

Method Summary

Modifier and TypeMethod and Description
private GeneralPath
boundingShape(double[] path0, double[] path1)

private void
private GeneralPath
caretBoundingShape(int caret0, int caret1, Rectangle2D bounds)

private boolean
caretIsValid(int caret)

private TextHitInfo

Returns:

a hit on this layout whose strong caret is at the requested index.
caretToHit
(int
a caret index.
caret
)

Given a caret index, return a hit whose caret is at the index.

private float
caretToPointDistance(float[] caretInfo, float x, float y)

Returns the distance from the point (x, y) to the caret along the line direction defined in caretInfo.

private void
protected Object
clone()

Overrides java.lang.Object.clone.

Creates a copy of this TextLayout.

public void
draw(Graphics2D
the Graphics2D context into which to render the layout
g2
,
float
the X coordinate of the origin of this TextLayout
x
,
float
the Y coordinate of the origin of this TextLayout
y
)

Renders this TextLayout at the specified location in the specified Graphics2D context.

private void
public boolean

Returns:

true if the specified TextLayout equals this TextLayout.
equals
(TextLayout
the TextLayout to compare to this TextLayout
rhs
)

Returns true if the two layouts are equal.

private void
fastInit(char[] chars, Font font, Map<? extends AttributedCharacterIterator.Attribute, ?> attrs, FontRenderContext frc)

public float

Returns:

the advance of this TextLayout.
getAdvance
()

Returns the advance of this TextLayout.

public float

Returns:

the ascent of this TextLayout.
getAscent
()

Returns the ascent of this TextLayout.

public byte

Returns:

the baseline of this TextLayout.
getBaseline
()

Returns the baseline for this TextLayout.

pack-priv static byte
public float[]

Returns:

the offsets array containing the baselines used for this TextLayout.
getBaselineOffsets
()

Returns the offsets array for the baselines used for this TextLayout.

public Shape

Returns:

a Shape enclosing the black box bounds. This is in standard coordinates.
getBlackBoxBounds
(int
one end of the character range
firstEndpoint
,
int
the other end of the character range. Can be less than firstEndpoint.
secondEndpoint
)

Returns the black box bounds of the characters in the specified range.

public Rectangle2D

Returns:

a Rectangle2D that is the bounds of this TextLayout.
getBounds
()

Returns the bounds of this TextLayout.

private float[]
getCaretInfo(int caret, Rectangle2D bounds, float[] info)

public float[]

Returns:

a two-element array containing the position and slope of the caret. The returned caret info is in baseline-relative coordinates.
getCaretInfo
(TextHitInfo
a hit on a character in this TextLayout
hit
,
Rectangle2D
the bounds to which the caret info is constructed. The bounds is in baseline-relative coordinates.
bounds
)

Returns information about the caret corresponding to hit.

public float[]

Returns:

the information about a caret corresponding to a hit. The returned caret info is in baseline-relative coordinates.
getCaretInfo
(TextHitInfo
a hit on a character in this TextLayout
hit
)

Returns information about the caret corresponding to hit.

private float[]
private double[]
private double[]
getCaretPath(int caret, Rectangle2D bounds, boolean clipToBounds)

Return an array of four floats corresponding the endpoints of the caret x0, y0, x1, y1.

public Shape

Returns:

a Shape representing the caret. The returned shape is in standard coordinates.
getCaretShape
(TextHitInfo
the hit at which to generate the caret
hit
,
Rectangle2D
the bounds of the TextLayout to use in generating the caret. The bounds is in baseline-relative coordinates.
bounds
)

Returns a Shape representing the caret at the specified hit inside the specified bounds.

public Shape

Returns:

a Shape representing the caret. The returned shape is in standard coordinates.
getCaretShape
(TextHitInfo
the hit at which to generate the caret
hit
)

Returns a Shape representing the caret at the specified hit inside the natural bounds of this TextLayout.

public Shape[]

Returns:

an array of two paths. Element zero is the strong caret. If there are two carets, element one is the weak caret, otherwise it is null. The returned shapes are in standard coordinates.
getCaretShapes
(int
an offset in this TextLayout
offset
,
Rectangle2D
the bounds to which to extend the carets. The bounds is in baseline-relative coordinates.
bounds
,
TextLayout.CaretPolicy
the specified CaretPolicy
policy
)

Returns two paths corresponding to the strong and weak caret.

public Shape[]

Returns:

two paths corresponding to the strong and weak caret as defined by the DEFAULT_CARET_POLICY. These are in standard coordinates.
getCaretShapes
(int
an offset in this TextLayout
offset
,
Rectangle2D
the bounds to which to extend the carets. This is in baseline-relative coordinates.
bounds
)

Returns two paths corresponding to the strong and weak caret.

public Shape[]

Returns:

two paths corresponding to the strong and weak caret as defined by the DEFAULT_CARET_POLICY. These are in standard coordinates.
getCaretShapes
(int
an offset in this TextLayout
offset
)

Returns two paths corresponding to the strong and weak caret.

public int

Returns:

the number of characters in this TextLayout.
getCharacterCount
()

Returns the number of characters represented by this TextLayout.

public byte

Returns:

the level of the character at the specified index.
getCharacterLevel
(int
the index of the character from which to get the level
index
)

Returns the level of the character at index.

public float

Returns:

the descent of this TextLayout.
getDescent
()

Returns the descent of this TextLayout.

public TextLayout

Returns:

a TextLayout justified to the specified width.
getJustifiedLayout
(float
the width to use when justifying the line. For best results, it should not be too different from the current advance of the line.
justificationWidth
)

Creates a copy of this TextLayout justified to the specified width.

public LayoutPath

Returns:

the layout path
getLayoutPath
()

Return the LayoutPath, or null if the layout path is the default path (x maps to advance, y maps to offset).

public float

Returns:

the leading of this TextLayout.
getLeading
()

Returns the leading of the TextLayout.

public Shape

Returns:

an area enclosing the selection. This is in standard coordinates.
getLogicalHighlightShape
(int
an endpoint in the range of characters to select
firstEndpoint
,
int
the other endpoint of the range of characters to select. Can be less than firstEndpoint. The range includes the character at min(firstEndpoint, secondEndpoint), but excludes max(firstEndpoint, secondEndpoint).
secondEndpoint
,
Rectangle2D
the bounding rectangle to which to extend the selection. This is in baseline-relative coordinates.
bounds
)

Returns a Shape enclosing the logical selection in the specified range, extended to the specified bounds.

public Shape

Returns:

a Shape enclosing the selection. This is in standard coordinates.
getLogicalHighlightShape
(int
an endpoint in the range of characters to select
firstEndpoint
,
int
the other endpoint of the range of characters to select. Can be less than firstEndpoint. The range includes the character at min(firstEndpoint, secondEndpoint), but excludes max(firstEndpoint, secondEndpoint).
secondEndpoint
)

Returns a Shape enclosing the logical selection in the specified range, extended to the natural bounds of this TextLayout.

public int[]

Returns:

an array of integers representing start/limit pairs for the selected ranges.
getLogicalRangesForVisualSelection
(TextHitInfo
an endpoint of the visual range
firstEndpoint
,
TextHitInfo
the other endpoint of the visual range. This endpoint can be less than firstEndpoint.
secondEndpoint
)

Returns the logical ranges of text corresponding to a visual selection.

private Rectangle2D
getNaturalBounds()

The 'natural bounds' encloses all the carets the layout can draw.

public TextHitInfo

Returns:

a hit whose caret appears at the next position to the left (top) of the caret of the provided hit, or null.
getNextLeftHit
(TextHitInfo
a hit on a character in this TextLayout.
hit
)

Returns the hit for the next caret to the left (top); if no such hit, returns null.

public TextHitInfo

Returns:

a hit whose caret appears at the next position to the left (top) of the caret of the provided hit, or null.
getNextLeftHit
(int
an insertion offset in this TextLayout. Cannot be less than 0 or greater than this TextLayout object's character count.
offset
,
TextLayout.CaretPolicy
the policy used to select the strong caret
policy
)

Returns the hit for the next caret to the left (top); if no such hit, returns null.

public TextHitInfo

Returns:

a hit whose caret appears at the next position to the left (top) of the caret of the provided hit, or null.
getNextLeftHit
(int
an insertion offset in this TextLayout. Cannot be less than 0 or greater than this TextLayout object's character count.
offset
)

Returns the hit for the next caret to the left (top); if no such hit, returns null.

public TextHitInfo

Returns:

a hit whose caret appears at the next position to the right (bottom) of the caret of the provided hit or null.
getNextRightHit
(TextHitInfo
a hit on a character in this layout
hit
)

Returns the hit for the next caret to the right (bottom); if there is no such hit, returns null.

public TextHitInfo

Returns:

a hit whose caret appears at the next position to the right (bottom) of the caret of the provided hit, or null.
getNextRightHit
(int
an insertion offset in this TextLayout. Cannot be less than 0 or greater than this TextLayout object's character count.
offset
,
TextLayout.CaretPolicy
the policy used to select the strong caret
policy
)

Returns the hit for the next caret to the right (bottom); if no such hit, returns null.

public TextHitInfo

Returns:

a hit whose caret appears at the next position to the right (bottom) of the caret of the provided hit, or null.
getNextRightHit
(int
an insertion offset in this TextLayout. Cannot be less than 0 or greater than the TextLayout object's character count.
offset
)

Returns the hit for the next caret to the right (bottom); if no such hit, returns null.

public Shape

Returns:

a Shape that is the outline of this TextLayout. This is in standard coordinates.
getOutline
(AffineTransform
an optional AffineTransform to apply to the outline of this TextLayout.
tx
)

Returns a Shape representing the outline of this TextLayout.

public Rectangle

Returns:

a Rectangle bounding the pixels that would be affected.
getPixelBounds
(FontRenderContext
the FontRenderContext of the Graphics.
frc
,
float
the x-coordinate at which to render this TextLayout.
x
,
float
the y-coordinate at which to render this TextLayout.
y
)

Returns the pixel bounds of this TextLayout when rendered in a graphics with the given FontRenderContext at the given location.

private TextHitInfo
getStrongHit(TextHitInfo hit1, TextHitInfo hit2)

Return the "stronger" of the TextHitInfos.

pack-priv TextLine
getTextLineForTesting()

Package-only method for testing ONLY.

public float

Returns:

the advance of this TextLayout without the trailing whitespace.
getVisibleAdvance
()

Returns the advance of this TextLayout, minus trailing whitespace.

public Shape

Returns:

a Shape enclosing the selection. This is in standard coordinates.
getVisualHighlightShape
(TextHitInfo
one end of the visual selection
firstEndpoint
,
TextHitInfo
the other end of the visual selection
secondEndpoint
,
Rectangle2D
the bounding rectangle to which to extend the selection. This is in baseline-relative coordinates.
bounds
)

Returns a path enclosing the visual selection in the specified range, extended to bounds.

public Shape

Returns:

a Shape enclosing the selection. This is in standard coordinates.
getVisualHighlightShape
(TextHitInfo
one end of the visual selection
firstEndpoint
,
TextHitInfo
the other end of the visual selection
secondEndpoint
)

Returns a Shape enclosing the visual selection in the specified range, extended to the bounds.

public TextHitInfo

Returns:

a hit that is on the opposite side of the specified hit's caret.
getVisualOtherHit
(TextHitInfo
the specified hit
hit
)

Returns the hit on the opposite side of the specified hit's caret.

protected void
handleJustify(float
the width to use when justifying the line. For best results, it should not be too different from the current advance of the line.
justificationWidth
)

Justify this layout.

public TextHitInfo

Returns:

a hit describing the character and edge (leading or trailing) under the specified point.
hitTestChar
(float
the x offset from the origin of this TextLayout. This is in standard coordinates.
x
,
float
the y offset from the origin of this TextLayout. This is in standard coordinates.
y
,
Rectangle2D
the bounds of the TextLayout. This is in baseline-relative coordinates.
bounds
)

Returns a TextHitInfo corresponding to the specified point.

public TextHitInfo

Returns:

a hit describing the character and edge (leading or trailing) under the specified point.
hitTestChar
(float
the x offset from the origin of this TextLayout. This is in standard coordinates.
x
,
float
the y offset from the origin of this TextLayout. This is in standard coordinates.
y
)

Returns a TextHitInfo corresponding to the specified point.

private int

Returns:

a caret index corresponding to the specified hit.
hitToCaret
(TextHitInfo
a hit on a character in this TextLayout
hit
)

Returns a caret index corresponding to hit.

public void
hitToPoint(TextHitInfo
the hit to check. This must be a valid hit on the TextLayout.
hit
,
Point2D
the returned point. The point is in standard coordinates.
point
)

Convert a hit to a point in standard coordinates.

public boolean

Returns:

true if the base direction of this TextLayout is left-to-right; false otherwise.
isLeftToRight
()

Returns true if this TextLayout has a left-to-right base direction or false if it has a right-to-left base direction.

public boolean

Returns:

true if this TextLayout is vertical; false otherwise.
isVertical
()

Returns true if this TextLayout is vertical.

private GeneralPath
private void
paragraphInit(byte aBaseline, CoreMetrics lm, Map<? extends AttributedCharacterIterator.Attribute, ?> paragraphAttrs, char[] text)

Initialize the paragraph-specific data.

private static GeneralPath
pathToShape(double[] path, boolean close, LayoutPathImpl lp)

private GeneralPath
private static int
sameBaselineUpTo(Font font, char[] text, int start, int limit)

Return the index of the first character with a different baseline from the character at start, or limit if all characters between start and limit have the same baseline.

private static Font
singleFont(char[] text, int start, int limit, Map<? extends AttributedCharacterIterator.Attribute, ?> attributes)

private void
public String

Returns:

the textLine of this TextLayout as a String.
toString
()

Overrides java.lang.Object.toString.

Returns debugging information for this TextLayout.

Inherited from java.lang.Object:
equalsfinalizegetClasshashCodenotifynotifyAllwaitwaitwait