All Packages  Class Hierarchy  This Package  Previous  Next  Index  

Class java.awt.font.TextLayout

java.lang.Object
    |
    +----java.awt.font.TextLayout

public final class TextLayout
extends Object
implements Cloneable
TextLayout is an immutable graphical representation of styled character data.

It provides the following capabilities:

TextLayout can be rendered by calling Graphics2D.drawString passing an instance of TextLayout and a position as the arguments.

TextLayout can be constructed either directly or through use of a LineBreakMeasurer. When constructed directly, the source text represents a single paragraph. LineBreakMeasurer provides support for line breaking to support wrapped text, see its documentation for more information.

TextLayout construction logically proceeds as follows:

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

TextLayouts 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 TextLayout (getNextRightHit, getNextLeftHit, and hitTestChar) return instances of TextHitInfo. The offsets contained in these TextHitInfo's are relative to the start of the TextLayout, not to the text used to create the TextLayout. Similarly, TextLayout methods which accept TextHitInfo instances as parameters expect the TextHitInfo'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");
   TextLayout layout = new TextLayout("This is a string", font);
   g.drawString(layout, loc.getX(), 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()));
 

Displaying every caret position in a layout. Also, this demonstrates how to correctly right-arrow from one TextHitInfo to another:

   AffineTransform translate = new AffineTransform();
   translate.setToTranslation(loc.getX(), loc.getY());
   TextHitInfo hit = new TextHitInfo(-1, TextHitInfo.TRAILING);
   for (; hit != null; hit = layout.getNextRightHit(hit)) {
       Shape[] shapes = layout.getCaretShapes(hit);
       Shape shape = shapes[0] == null? shapes[1] : shapes[0];

       shape = translate.createTransformedShape(shape);
       g.draw(shape);
   }
 

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
   selection = translation.createTransformedShape(selection);
   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():

   TextOffset selStart = ..., selLimit = ...;
   Shape selection = layout.getVisualHighlightSelection(selStart, selLimit);
   selection = translation.createTransformedShape(selection);
   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.
 

See Also:
LineBreakMeasurer, TextAttributeSet, TextHitInfo

Constructor Index

 o TextLayout(AttributedCharacterIterator)
Construct a layout from an iterator over styled text.
 o TextLayout(String, AttributeSet)
Construct a layout from a string and an attribute set.
 o TextLayout(String, Font)
Construct a layout from a string and a font.
 o TextLayout(StyledString)
Construct a layout from a styled string.

Method Index

 o clone()
Create a copy of this layout.
 o draw(Graphics2D, float, float)
Render the layout at the provided location in the graphics.
 o equals(Object)
Return true if the object is a TextLayout and this equals the object.
 o equals(TextLayout)
Return true if the two layouts are equal.
 o getAdvance()
Return the advance of the layout.
 o getAscent()
Return the ascent of the layout.
 o getBaseline()
Return the baseline for this layout.
 o getBaselineOffsets()
Return the offsets array for the baselines used for this layout.
 o getBlackBoxBounds(int, int)
Return the black box bounds of the characters between start and limit.
 o getBounds()
Return the bounds of the layout.
 o getCaretInfo(TextHitInfo)
Return information about the caret corresponding to hit.
 o getCaretShapes(TextHitInfo)
A convenience overload that uses the natural bounds of the layout as the bounds.
 o getCaretShapes(TextHitInfo, Rectangle2D)
Return two paths corresponding to the strong and weak caret.
 o getCharacterCount()
Return the number of characters represented by this layout.
 o getDescent()
Return the descent of the layout.
 o getJustifiedLayout(float)
Create a copy of this layout justified to the given width.
 o getLeading()
Return the leading of the layout.
 o getLogicalHighlightShape(int, int)
A convenience overload which uses the natural bounds of the layout.
 o getLogicalHighlightShape(int, int, Rectangle2D)
Return a path enclosing the logical selection between start and limit, extended to bounds.
 o getLogicalRangesForVisualSelection(TextHitInfo, TextHitInfo)
Return the logical ranges of text corresponding to a visual selection.
 o getNextLeftHit(TextHitInfo)
Return the hit for the next strong caret to the left (top); if no such hit, return null.
 o getNextRightHit(TextHitInfo)
Return the hit for the next strong caret to the right (bottom); if no such hit, return null.
 o getVisibleAdvance()
Return the advance of the layout, minus trailing whitespace.
 o getVisualHighlightShape(TextHitInfo, TextHitInfo)
A convenience overload which uses the natural bounds of the layout.
 o getVisualHighlightShape(TextHitInfo, TextHitInfo, Rectangle2D)
Return a path enclosing the visual selection between start and limit, extended to bounds.
 o handleJustify(float)
Justify this layout.
 o hashCode()
Return the hash code of this layout.
 o hitTestChar(float, float)
Return a TextHitInfo corresponding to the point.
 o isLeftToRight()
Return true if the layout is left-to-right.
 o isVertical()
Return true if the layout is vertical.
 o toString()
Display the glyphsets contained in the layout, for debugging only.

Constructors

 o TextLayout
public TextLayout(String string,
                  Font font)
Construct a layout from a string and a font. All the text is styled using the provided font. The string must specify a single paragraph of text, as an entire paragraph is required for the bidirectional algorithm.

Parameters:
str - the text to display.
font - a font used to style the text.
 o TextLayout
public TextLayout(String string,
                  AttributeSet attributes)
Construct a layout from a string and an attribute set.

All the text is styled using the provided attributes.

The string must specify a single paragraph of text, as an entire paragraph is required for the bidirectional algorithm.

Parameters:
str - the text to display.
attributes - the attributes used to style the text.
 o TextLayout
public TextLayout(StyledString text)
Construct a layout from a styled string.

The text must specify a single paragraph of text, as an entire paragraph is required for the bidirectional algorithm.

Parameters:
text - the styled text to display.
 o TextLayout
public TextLayout(AttributedCharacterIterator text)
Construct a layout from an iterator over styled text.

The iterator must specify a single paragraph of text, as an entire paragraph is required for the bidirectional algorithm.

Parameters:
text - the styled text to display.

Methods

 o clone
protected Object clone()
Create a copy of this layout.

Overrides:
clone in class Object
 o getJustifiedLayout
public TextLayout getJustifiedLayout(float justificationWidth)
Create a copy of this layout justified to the given width.

If this layout has already been justified, an exception is thrown. If this layout's justification ratio is zero, a layout identical to this one is returned.

Parameters:
justificationWidth - the width to use when justifying the line. For best results, it should not be too different from the current advance of the line.
Returns:
a layout justified to the given width.
Throws: Error
if this layout has already been justified, an Error is thrown.
 o handleJustify
protected void handleJustify(float justificationWidth)
Justify this layout. Overridden by subclassers to control justification. The layout will only justify if the paragraph attributes (from the source text, possibly defaulted by the layout attributes) indicate a non-zero justification ratio. The text will be justified to the indicated width. The current implementation also adjusts hanging punctuation and trailing whitespace to overhang the justification width. Once justified, the layout may not be rejustified.

Some code may rely on immutablity of layouts. Subclassers should not call this directly, but instead should call getJustifiedLayout, which will call this method on a clone of this layout, preserving the original.

Parameters:
justificationWidth - the width to use when justifying the line. For best results, it should not be too different from the current advance of the line.
See Also:
getJustifiedLayout
 o getBaseline
public byte getBaseline()
Return the baseline for this layout. The baseline is one of the values defined in Font (roman, centered, hanging). Ascent and descent are relative to this baseline. The baselineOffsets are also relative to this baseline.

See Also:
getBaselineOffsets, Font
 o getBaselineOffsets
public float[] getBaselineOffsets()
Return the offsets array for the baselines used for this layout.

The array is indexed by one of the values defined in Font (roman, centered, hanging). The values are relative to this layout's baseline, so that getBaselineOffsets[getBaseline()] == 0. Offsets are added to the position of the layout's baseline to get the position for the new baseline.

See Also:
getBaseline, Font
 o getAdvance
public float getAdvance()
Return the advance of the layout. The advance is the distance from the origin to the advance of the rightmost (bottommost) character measuring in the line direction.

 o getVisibleAdvance
public float getVisibleAdvance()
Return the advance of the layout, minus trailing whitespace.

See Also:
getAdvance
 o getAscent
public float getAscent()
Return the ascent of the layout. The ascent is the distance from the top (right) of the layout to the baseline. It is always positive or zero. The ascent is sufficient to accomodate superscripted text and is the maximum of the sum of the the ascent, offset, and baseline of each glyph.

 o getDescent
public float getDescent()
Return the descent of the layout. The descent is the distance from the baseline to the bottom (left) of the layout. It is always positive or zero. The descent is sufficient to accomodate subscripted text and is maximum of the sum of the descent, offset, and baseline of each glyph.

 o getLeading
public float getLeading()
Return the leading of the layout. The leading is the suggested interline spacing for this layout.

The leading is computed from the leading, descent, and baseline of all glyphsets in the layout. The algorithm is roughly as follows:

 maxD = 0;
 maxDL = 0;
 for (GlyphSet g in all glyphsets) {
    maxD = max(maxD, g.getDescent() + offsets[g.getBaseline()]);
    maxDL = max(maxDL, g.getDescent() + g.getLeading() + 
                       offsets[g.getBaseline()]);
 }
 return maxDL - maxD;
 

 o getBounds
public Rectangle2D getBounds()
Return the bounds of the layout. This bounds all space that can be drawn on by text or carets. It extends from ascent to descent + leading, and from the left (top) edge of the first character to the right (bottom) edge of the last. If there is hanging punctuation, the left (top) of the bounds may be negative.

 o isLeftToRight
public boolean isLeftToRight()
Return true if the layout is left-to-right. The layout has a base direction of either left-to-right (LTR) or right-to-left (RTL). This is independent of the actual direction of text on the line, which may be either or mixed. Left-to-right layouts by default should position flush left, and if on a tabbed line, the tabs run left to right, so that logically successive layouts position left to right. The opposite is true for RTL layouts. By default they should position flush left, and tabs run right-to-left. On vertical lines all text runs top-to-bottom, and is treated as LTR.

 o isVertical
public boolean isVertical()
Return true if the layout is vertical.

 o getCharacterCount
public int getCharacterCount()
Return the number of characters represented by this layout.

 o getCaretInfo
public float[] getCaretInfo(TextHitInfo hit)
Return information about the caret corresponding to hit. The first element of the array is the intersection of the caret with the baseline. The second element of the array is the slope (run/rise) of the caret.

This method is meant for informational use. To display carets, it is better to use getCaretShapes.

Parameters:
hit - a hit on a character in this layout
Returns:
a two-element array containing the position and slope of the caret
See Also:
getCaretShapes
 o getNextRightHit
public TextHitInfo getNextRightHit(TextHitInfo hit)
Return the hit for the next strong caret to the right (bottom); if no such hit, return null. If the hit character index is out of bounds, an IllegalArgumentException is thrown.

Parameters:
hit - a hit on a character in this layout.
Returns:
a hit whose strong caret appears at the next position to the right (bottom) of the strong caret of the provided hit, or null.
 o getNextLeftHit
public TextHitInfo getNextLeftHit(TextHitInfo hit)
Return the hit for the next strong caret to the left (top); if no such hit, return null. If the hit character index is out of bounds, an IllegalArgumentException is thrown.

Parameters:
hit - a hit on a character in this layout.
Returns:
a hit whose strong caret appears at the next position to the left (top) of the strong caret of the provided hit, or null.
 o getCaretShapes
public Shape[] getCaretShapes(TextHitInfo hit,
                              Rectangle2D bounds)
Return two paths corresponding to the strong and weak caret.

Parameters:
hit - a hit on a character in this layout
bounds - the bounds to which to extend the carets
Returns:
an array of two paths. Element zero is the strong caret (if any) or null. Element one is the weak caret (if any) or null. Element 0 and element 1 are never both null.
 o getCaretShapes
public Shape[] getCaretShapes(TextHitInfo hit)
A convenience overload that uses the natural bounds of the layout as the bounds.

 o getLogicalRangesForVisualSelection
public int[] getLogicalRangesForVisualSelection(TextHitInfo startHit,
                                                TextHitInfo limitHit)
Return the logical ranges of text corresponding to a visual selection.

Parameters:
startHit - the start of the visual range
limitHit - the end of the visual range
Returns:
an array of integers representing start/limit pairs for the selected ranges
See Also:
getVisualHighlightShape
 o getVisualHighlightShape
public Shape getVisualHighlightShape(TextHitInfo startHit,
                                     TextHitInfo limitHit,
                                     Rectangle2D bounds)
Return a path enclosing the visual selection between start and limit, extended to bounds.

If the selection includes the leftmost (topmost) position, the selection is extended to the left (top) of the bounds. If the selection includes the rightmost (bottommost) position, the selection is extended to the right (bottom) of the bounds. The height (width on vertical lines) of the selection is always extended to bounds.

Although the selection is always contiguous, the logically selected text can be discontiguous on lines with mixed-direction text. The logical ranges of text selected can be retrieved using getLogicalRangesForVisualSelection. For example, consider the text 'ABCdef' where capital letters indicate right-to-left text, rendered on a right-to-left line, with a visual selection from 0L (the leading edge of 'A') to 3T (the trailing edge of 'd'). The text appears as follows, with bold underlined areas representing the selection:

    defCBA  
 
The logical selection ranges are 0-3, 4-6 (ABC, ef) because the visually contiguous text is logically discontiguous. Also note that since the rightmost position on the layout (to the right of 'A') is selected, the selection is extended to the right of the bounds.

Parameters:
startHit - the start of the visual selection
limitHit - the limit of the visual selection
bounds - the bounding rectangle to which to extend the selection
Returns:
an area enclosing the selection
See Also:
getLogicalRangesForVisualSelection, getLogicalHighlightShape
 o getVisualHighlightShape
public Shape getVisualHighlightShape(TextHitInfo startHit,
                                     TextHitInfo limitHit)
A convenience overload which uses the natural bounds of the layout.

 o getLogicalHighlightShape
public Shape getLogicalHighlightShape(int start,
                                      int limit,
                                      Rectangle2D bounds)
Return a path enclosing the logical selection between start and limit, extended to bounds.

If the selection range includes the first logical character, the selection is extended to the portion of bounds before the start of the layout. If the range includes the last logical character, the selection is extended to the portion of bounds after the end of the layout. The height (width on vertical lines) of the selection is always extended to bounds.

The selection can be discontiguous on lines with mixed-direction text. Only those characters in the logical range between start and limit will appear selected. For example consider the text 'ABCdef' where capital letters indicate right-to-left text, rendered on a right-to-left line, with a logical selection from 0 to 4 ('ABCd'). The text appears as follows, with bold standing in for the selection, and underlining for the extension:

    defCBA  
 
The selection is discontiguous because the selected characters are visually discontiguous. Also note that since the range includes the first logical character (A), the selection is extended to the portion of the bounds before the start of the layout, which in this case (a right-to-left line) is the right portion of the bounds.

Parameters:
start - the start of the range of characters to select
limit - the limit of the range of characters to select
bounds - the bounding rectangle to which to extend the selection
Returns:
an area enclosing the selection
See Also:
getVisualHighlightShape
 o getLogicalHighlightShape
public Shape getLogicalHighlightShape(int start,
                                      int limit)
A convenience overload which uses the natural bounds of the layout.

 o getBlackBoxBounds
public Shape getBlackBoxBounds(int start,
                               int limit)
Return the black box bounds of the characters between start and limit. The black box bounds is an area consisting of the union of the bounding boxes of all the glyphs corresponding to the characters between start and limit. This path may be disjoint.

Parameters:
start - the index of the first character to include in the bounds
limit - the index past the last character to include in the bounds
Returns:
a path enclosing the black box bounds
 o hitTestChar
public TextHitInfo hitTestChar(float x,
                               float y)
Return a TextHitInfo corresponding to the point. Coordinates outside the bounds of the layout map to hits on the leading edge of the first logical character, or the trailing edge of the last logical character, as appropriate, regardless of the position of that character in the line. Only the direction along the baseline is used to make this evaluation.

Parameters:
x - the x offset from the origin of the layout
y - the y offset from the origin of the layout
Returns:
a hit describing the character and edge (leading or trailing) under the point
 o hashCode
public int hashCode()
Return the hash code of this layout.

Overrides:
hashCode in class Object
 o equals
public boolean equals(Object obj)
Return true if the object is a TextLayout and this equals the object.

Overrides:
equals in class Object
 o equals
public boolean equals(TextLayout layout)
Return true if the two layouts are equal. Two layouts are equal if they contain equal glyphsets in the same order.

Parameters:
layout - the layout to which to compare this layout.
 o toString
public String toString()
Display the glyphsets contained in the layout, for debugging only.

Overrides:
toString in class Object
 o draw
public void draw(Graphics2D g2,
                 float x,
                 float y)
Render the layout at the provided location in the graphics. The origin of the layout is placed at x, y. Rendering may touch any point within getBounds() of this position. This leaves the graphics unchanged.

Parameters:
g2 - the graphics into which to render the layout
x - the x position for the origin of the layout
y - the y position for the origin of the layout
See Also:
getBounds

All Packages  Class Hierarchy  This Package  Previous  Next  Index  

Submit a bug or feature