Liking cljdoc? Tell your friends :D

jdk.awt.font.core

No vars found in this namespace.

jdk.awt.font.FontRenderContext

The FontRenderContext class is a container for the information needed to correctly measure text. The measurement of text can vary because of rules that map outlines to pixels, and rendering hints provided by an application.

One such piece of information is a transform that scales typographical points to pixels. (A point is defined to be exactly 1/72 of an inch, which is slightly different than the traditional mechanical measurement of a point.) A character that is rendered at 12pt on a 600dpi device might have a different size than the same character rendered at 12pt on a 72dpi device because of such factors as rounding to pixel boundaries and hints that the font designer may have specified.

Anti-aliasing and Fractional-metrics specified by an application can also affect the size of a character because of rounding to pixel boundaries.

Typically, instances of FontRenderContext are obtained from a Graphics2D object. A FontRenderContext which is directly constructed will most likely not represent any actual graphics device, and may lead to unexpected or incorrect results.

The FontRenderContext class is a container for the
information needed to correctly measure text.  The measurement of text
can vary because of rules that map outlines to pixels, and rendering
hints provided by an application.

One such piece of information is a transform that scales
typographical points to pixels. (A point is defined to be exactly 1/72
of an inch, which is slightly different than
the traditional mechanical measurement of a point.)  A character that
is rendered at 12pt on a 600dpi device might have a different size
than the same character rendered at 12pt on a 72dpi device because of
such factors as rounding to pixel boundaries and hints that the font
designer may have specified.

Anti-aliasing and Fractional-metrics specified by an application can also
affect the size of a character because of rounding to pixel
boundaries.

Typically, instances of FontRenderContext are
obtained from a Graphics2D object.  A
FontRenderContext which is directly constructed will
most likely not represent any actual graphics device, and may lead
to unexpected or incorrect results.
raw docstring

jdk.awt.font.GlyphJustificationInfo

The GlyphJustificationInfo class represents information about the justification properties of a glyph. A glyph is the visual representation of one or more characters. Many different glyphs can be used to represent a single character or combination of characters. The four justification properties represented by GlyphJustificationInfo are weight, priority, absorb and limit.

Weight is the overall 'weight' of the glyph in the line. Generally it is proportional to the size of the font. Glyphs with larger weight are allocated a correspondingly larger amount of the change in space.

Priority determines the justification phase in which this glyph is used. All glyphs of the same priority are examined before glyphs of the next priority. If all the change in space can be allocated to these glyphs without exceeding their limits, then glyphs of the next priority are not examined. There are four priorities, kashida, whitespace, interchar, and none. KASHIDA is the first priority examined. NONE is the last priority examined.

Absorb determines whether a glyph absorbs all change in space. Within a given priority, some glyphs may absorb all the change in space. If any of these glyphs are present, no glyphs of later priority are examined.

Limit determines the maximum or minimum amount by which the glyph can change. Left and right sides of the glyph can have different limits.

Each GlyphJustificationInfo represents two sets of metrics, which are growing and shrinking. Growing metrics are used when the glyphs on a line are to be spread apart to fit a larger width. Shrinking metrics are used when the glyphs are to be moved together to fit a smaller width.

The GlyphJustificationInfo class represents information
about the justification properties of a glyph.  A glyph is the visual
representation of one or more characters.  Many different glyphs can
be used to represent a single character or combination of characters.
The four justification properties represented by
GlyphJustificationInfo are weight, priority, absorb and
limit.

Weight is the overall 'weight' of the glyph in the line.  Generally it is
proportional to the size of the font.  Glyphs with larger weight are
allocated a correspondingly larger amount of the change in space.

Priority determines the justification phase in which this glyph is used.
All glyphs of the same priority are examined before glyphs of the next
priority.  If all the change in space can be allocated to these glyphs
without exceeding their limits, then glyphs of the next priority are not
examined. There are four priorities, kashida, whitespace, interchar,
and none.  KASHIDA is the first priority examined. NONE is the last
priority examined.

Absorb determines whether a glyph absorbs all change in space.  Within a
given priority, some glyphs may absorb all the change in space.  If any of
these glyphs are present, no glyphs of later priority are examined.

Limit determines the maximum or minimum amount by which the glyph can
change. Left and right sides of the glyph can have different limits.

Each GlyphJustificationInfo represents two sets of
metrics, which are growing and shrinking.  Growing
metrics are used when the glyphs on a line are to be
spread apart to fit a larger width.  Shrinking metrics are used when
the glyphs are to be moved together to fit a smaller width.
raw docstring

jdk.awt.font.GlyphMetrics

The GlyphMetrics class represents information for a single glyph. A glyph is the visual representation of one or more characters. Many different glyphs can be used to represent a single character or combination of characters. GlyphMetrics instances are produced by Font and are applicable to a specific glyph in a particular Font.

Glyphs are either STANDARD, LIGATURE, COMBINING, or COMPONENT.

STANDARD glyphs are commonly used to represent single characters. LIGATURE glyphs are used to represent sequences of characters. COMPONENT glyphs in a GlyphVector do not correspond to a particular character in a text model. Instead, COMPONENT glyphs are added for typographical reasons, such as Arabic justification. COMBINING glyphs embellish STANDARD or LIGATURE glyphs, such as accent marks. Carets do not appear before COMBINING glyphs.

Other metrics available through GlyphMetrics are the components of the advance, the visual bounds, and the left and right side bearings.

Glyphs for a rotated font, or obtained from a GlyphVector which has applied a rotation to the glyph, can have advances that contain both X and Y components. Usually the advance only has one component.

The advance of a glyph is the distance from the glyph's origin to the origin of the next glyph along the baseline, which is either vertical or horizontal. Note that, in a GlyphVector, the distance from a glyph to its following glyph might not be the glyph's advance, because of kerning or other positioning adjustments.

The bounds is the smallest rectangle that completely contains the outline of the glyph. The bounds rectangle is relative to the glyph's origin. The left-side bearing is the distance from the glyph origin to the left of its bounds rectangle. If the left-side bearing is negative, part of the glyph is drawn to the left of its origin. The right-side bearing is the distance from the right side of the bounds rectangle to the next glyph origin (the origin plus the advance). If negative, part of the glyph is drawn to the right of the next glyph's origin. Note that the bounds does not necessarily enclose all the pixels affected when rendering the glyph, because of rasterization and pixel adjustment effects.

Although instances of GlyphMetrics can be directly constructed, they are almost always obtained from a GlyphVector. Once constructed, GlyphMetrics objects are immutable.

Example: Querying a Font for glyph information

Font font = ...; int glyphIndex = ...; GlyphMetrics metrics = GlyphVector.getGlyphMetrics(glyphIndex); int isStandard = metrics.isStandard(); float glyphAdvance = metrics.getAdvance();

The GlyphMetrics class represents information for a
single glyph.   A glyph is the visual representation of one or more
characters.  Many different glyphs can be used to represent a single
character or combination of characters.  GlyphMetrics
instances are produced by Font and are applicable
to a specific glyph in a particular Font.

Glyphs are either STANDARD, LIGATURE, COMBINING, or COMPONENT.

STANDARD glyphs are commonly used to represent single characters.
LIGATURE glyphs are used to represent sequences of characters.
COMPONENT glyphs in a GlyphVector do not correspond to a
particular character in a text model. Instead, COMPONENT glyphs are
added for typographical reasons, such as Arabic justification.
COMBINING glyphs embellish STANDARD or LIGATURE glyphs, such
as accent marks.  Carets do not appear before COMBINING glyphs.


Other metrics available through GlyphMetrics are the
components of the advance, the visual bounds, and the left and right
side bearings.

Glyphs for a rotated font, or obtained from a GlyphVector
which has applied a rotation to the glyph, can have advances that
contain both X and Y components.  Usually the advance only has one
component.

The advance of a glyph is the distance from the glyph's origin to the
origin of the next glyph along the baseline, which is either vertical
or horizontal.  Note that, in a GlyphVector,
the distance from a glyph to its following glyph might not be the
glyph's advance, because of kerning or other positioning adjustments.

The bounds is the smallest rectangle that completely contains the
outline of the glyph.  The bounds rectangle is relative to the
glyph's origin.  The left-side bearing is the distance from the glyph
origin to the left of its bounds rectangle. If the left-side bearing is
negative, part of the glyph is drawn to the left of its origin.  The
right-side bearing is the distance from the right side of the bounds
rectangle to the next glyph origin (the origin plus the advance).  If
negative, part of the glyph is drawn to the right of the next glyph's
origin.  Note that the bounds does not necessarily enclose all the pixels
affected when rendering the glyph, because of rasterization and pixel
adjustment effects.

Although instances of GlyphMetrics can be directly
constructed, they are almost always obtained from a
GlyphVector.  Once constructed, GlyphMetrics
objects are immutable.

Example:
Querying a Font for glyph information


Font font = ...;
int glyphIndex = ...;
GlyphMetrics metrics = GlyphVector.getGlyphMetrics(glyphIndex);
int isStandard = metrics.isStandard();
float glyphAdvance = metrics.getAdvance();
raw docstring

jdk.awt.font.GlyphVector

A GlyphVector object is a collection of glyphs containing geometric information for the placement of each glyph in a transformed coordinate space which corresponds to the device on which the GlyphVector is ultimately displayed.

The GlyphVector does not attempt any interpretation of the sequence of glyphs it contains. Relationships between adjacent glyphs in sequence are solely used to determine the placement of the glyphs in the visual coordinate space.

Instances of GlyphVector are created by a Font.

In a text processing application that can cache intermediate representations of text, creation and subsequent caching of a GlyphVector for use during rendering is the fastest method to present the visual representation of characters to a user.

A GlyphVector is associated with exactly one Font, and can provide data useful only in relation to this Font. In addition, metrics obtained from a GlyphVector are not generally geometrically scaleable since the pixelization and spacing are dependent on grid-fitting algorithms within a Font. To facilitate accurate measurement of a GlyphVector and its component glyphs, you must specify a scaling transform, anti-alias mode, and fractional metrics mode when creating the GlyphVector. These characteristics can be derived from the destination device.

For each glyph in the GlyphVector, you can obtain:

the position of the glyph the transform associated with the glyph the metrics of the glyph in the context of the GlyphVector. The metrics of the glyph may be different under different transforms, application specified rendering hints, and the specific instance of the glyph within the GlyphVector.

Altering the data used to create the GlyphVector does not alter the state of the GlyphVector.

Methods are provided to adjust the positions of the glyphs within the GlyphVector. These methods are most appropriate for applications that are performing justification operations for the presentation of the glyphs.

Methods are provided to transform individual glyphs within the GlyphVector. These methods are primarily useful for special effects.

Methods are provided to return both the visual, logical, and pixel bounds of the entire GlyphVector or of individual glyphs within the GlyphVector.

Methods are provided to return a Shape for the GlyphVector, and for individual glyphs within the GlyphVector.

A GlyphVector object is a collection of glyphs
containing geometric information for the placement of each glyph
in a transformed coordinate space which corresponds to the
device on which the GlyphVector is ultimately
displayed.

The GlyphVector does not attempt any interpretation of
the sequence of glyphs it contains.  Relationships between adjacent
glyphs in sequence are solely used to determine the placement of
the glyphs in the visual coordinate space.

Instances of GlyphVector are created by a Font.

In a text processing application that can cache intermediate
representations of text, creation and subsequent caching of a
GlyphVector for use during rendering is the fastest
method to present the visual representation of characters to a user.

A GlyphVector is associated with exactly one
Font, and can provide data useful only in relation to
this Font.  In addition, metrics obtained from a
GlyphVector are not generally geometrically scaleable
since the pixelization and spacing are dependent on grid-fitting
algorithms within a Font.  To facilitate accurate
measurement of a GlyphVector and its component
glyphs, you must specify a scaling transform, anti-alias mode, and
fractional metrics mode when creating the GlyphVector.
These characteristics can be derived from the destination device.

For each glyph in the GlyphVector, you can obtain:

the position of the glyph
the transform associated with the glyph
the metrics of the glyph in the context of the
  GlyphVector.  The metrics of the glyph may be
  different under different transforms, application specified
  rendering hints, and the specific instance of the glyph within
  the GlyphVector.


Altering the data used to create the GlyphVector does not
alter the state of the GlyphVector.

Methods are provided to adjust the positions of the glyphs
within the GlyphVector.  These methods are most
appropriate for applications that are performing justification
operations for the presentation of the glyphs.

Methods are provided to transform individual glyphs within the
GlyphVector.  These methods are primarily useful for
special effects.

Methods are provided to return both the visual, logical, and pixel bounds
of the entire GlyphVector or of individual glyphs within
the GlyphVector.

Methods are provided to return a Shape for the
GlyphVector, and for individual glyphs within the
GlyphVector.
raw docstring

jdk.awt.font.GraphicAttribute

This class is used with the CHAR_REPLACEMENT attribute.

The GraphicAttribute class represents a graphic embedded in text. Clients subclass this class to implement their own char replacement graphics. Clients wishing to embed shapes and images in text need not subclass this class. Instead, clients can use the ShapeGraphicAttribute and ImageGraphicAttribute classes.

Subclasses must ensure that their objects are immutable once they are constructed. Mutating a GraphicAttribute that is used in a TextLayout results in undefined behavior from the TextLayout.

This class is used with the CHAR_REPLACEMENT attribute.

The GraphicAttribute class represents a graphic embedded
in text. Clients subclass this class to implement their own char
replacement graphics.  Clients wishing to embed shapes and images in
text need not subclass this class.  Instead, clients can use the
ShapeGraphicAttribute and ImageGraphicAttribute
classes.

Subclasses must ensure that their objects are immutable once they
are constructed.  Mutating a GraphicAttribute that
is used in a TextLayout results in undefined behavior from the
TextLayout.
raw docstring

jdk.awt.font.ImageGraphicAttribute

The ImageGraphicAttribute class is an implementation of GraphicAttribute which draws images in a TextLayout.

The ImageGraphicAttribute class is an implementation of
GraphicAttribute which draws images in
a TextLayout.
raw docstring

jdk.awt.font.LayoutPath

LayoutPath provides a mapping between locations relative to the baseline and points in user space. Locations consist of an advance along the baseline, and an offset perpendicular to the baseline at the advance. Positive values along the perpendicular are in the direction that is 90 degrees clockwise from the baseline vector. Locations are represented as a Point2D, where x is the advance and y is the offset.

LayoutPath provides a mapping between locations relative to the
baseline and points in user space.  Locations consist of an advance
along the baseline, and an offset perpendicular to the baseline at
the advance.  Positive values along the perpendicular are in the
direction that is 90 degrees clockwise from the baseline vector.
Locations are represented as a Point2D, where x is the advance and
y is the offset.
raw docstring

jdk.awt.font.LineBreakMeasurer

The LineBreakMeasurer class allows styled text to be broken into lines (or segments) that fit within a particular visual advance. This is useful for clients who wish to display a paragraph of text that fits within a specific width, called the wrapping width.

LineBreakMeasurer is constructed with an iterator over styled text. The iterator's range should be a single paragraph in the text. LineBreakMeasurer maintains a position in the text for the start of the next text segment. Initially, this position is the start of text. Paragraphs are assigned an overall direction (either left-to-right or right-to-left) according to the bidirectional formatting rules. All segments obtained from a paragraph have the same direction as the paragraph.

Segments of text are obtained by calling the method nextLayout, which returns a TextLayout representing the text that fits within the wrapping width. The nextLayout method moves the current position to the end of the layout returned from nextLayout.

LineBreakMeasurer implements the most commonly used line-breaking policy: Every word that fits within the wrapping width is placed on the line. If the first word does not fit, then all of the characters that fit within the wrapping width are placed on the line. At least one character is placed on each line.

The TextLayout instances returned by LineBreakMeasurer treat tabs like 0-width spaces. Clients who wish to obtain tab-delimited segments for positioning should use the overload of nextLayout which takes a limiting offset in the text. The limiting offset should be the first character after the tab. The TextLayout objects returned from this method end at the limit provided (or before, if the text between the current position and the limit won't fit entirely within the wrapping width).

Clients who are laying out tab-delimited text need a slightly different line-breaking policy after the first segment has been placed on a line. Instead of fitting partial words in the remaining space, they should place words which don't fit in the remaining space entirely on the next line. This change of policy can be requested in the overload of nextLayout which takes a boolean parameter. If this parameter is true, nextLayout returns null if the first word won't fit in the given space. See the tab sample below.

In general, if the text used to construct the LineBreakMeasurer changes, a new LineBreakMeasurer must be constructed to reflect the change. (The old LineBreakMeasurer continues to function properly, but it won't be aware of the text change.) Nevertheless, if the text change is the insertion or deletion of a single character, an existing LineBreakMeasurer can be 'updated' by calling insertChar or deleteChar. Updating an existing LineBreakMeasurer is much faster than creating a new one. Clients who modify text based on user typing should take advantage of these methods.

Examples: Rendering a paragraph in a component

public void paint(Graphics graphics) {

Point2D pen = new Point2D(10, 20);
Graphics2D g2d = (Graphics2D)graphics;
FontRenderContext frc = g2d.getFontRenderContext();

// let styledText be an AttributedCharacterIterator containing at least
// one character

LineBreakMeasurer measurer = new LineBreakMeasurer(styledText, frc);
float wrappingWidth = getSize().width - 15;

while (measurer.getPosition() < fStyledText.length()) {

    TextLayout layout = measurer.nextLayout(wrappingWidth);

    pen.y = (layout.getAscent());
    float dx = layout.isLeftToRight() ?
        0 : (wrappingWidth - layout.getAdvance());

    layout.draw(graphics, pen.x  dx, pen.y);
    pen.y = layout.getDescent()  layout.getLeading();
}

}

Rendering text with tabs. For simplicity, the overall text direction is assumed to be left-to-right

public void paint(Graphics graphics) {

float leftMargin = 10, rightMargin = 310;
float[] tabStops = { 100, 250 };

// assume styledText is an AttributedCharacterIterator, and the number
// of tabs in styledText is tabCount

int[] tabLocations = new int[tabCount+1];

int i = 0;
for (char c = styledText.first(); c != styledText.DONE; c = styledText.next()) {
    if (c == '\t') {
        tabLocations[i++] = styledText.getIndex();
    }
}
tabLocations[tabCount] = styledText.getEndIndex() - 1;

// Now tabLocations has an entry for every tab's offset in
// the text.  For convenience, the last entry is tabLocations
// is the offset of the last character in the text.

LineBreakMeasurer measurer = new LineBreakMeasurer(styledText);
int currentTab = 0;
float verticalPos = 20;

while (measurer.getPosition() < styledText.getEndIndex()) {

    // Lay out and draw each line.  All segments on a line
    // must be computed before any drawing can occur, since
    // we must know the largest ascent on the line.
    // TextLayouts are computed and stored in a Vector;
    // their horizontal positions are stored in a parallel
    // Vector.

    // lineContainsText is true after first segment is drawn
    boolean lineContainsText = false;
    boolean lineComplete = false;
    float maxAscent = 0, maxDescent = 0;
    float horizontalPos = leftMargin;
    Vector layouts = new Vector(1);
    Vector penPositions = new Vector(1);

    while (!lineComplete) {
        float wrappingWidth = rightMargin - horizontalPos;
        TextLayout layout =
                measurer.nextLayout(wrappingWidth,
                                    tabLocations[currentTab]+1,
                                    lineContainsText);

        // layout can be null if lineContainsText is true
        if (layout != null) {
            layouts.addElement(layout);
            penPositions.addElement(new Float(horizontalPos));
            horizontalPos = layout.getAdvance();
            maxAscent = Math.max(maxAscent, layout.getAscent());
            maxDescent = Math.max(maxDescent,
                layout.getDescent()  layout.getLeading());
        } else {
            lineComplete = true;
        }

        lineContainsText = true;

        if (measurer.getPosition() == tabLocations[currentTab]+1) {
            currentTab++;
        }

        if (measurer.getPosition() == styledText.getEndIndex())
            lineComplete = true;
        else if (horizontalPos >= tabStops[tabStops.length-1])
            lineComplete = true;

        if (!lineComplete) {
            // move to next tab stop
            int j;
            for (j=0; horizontalPos >= tabStops[j]; j++) {}
            horizontalPos = tabStops[j];
        }
    }

    verticalPos = maxAscent;

    Enumeration layoutEnum = layouts.elements();
    Enumeration positionEnum = penPositions.elements();

    // now iterate through layouts and draw them
    while (layoutEnum.hasMoreElements()) {
        TextLayout nextLayout = (TextLayout) layoutEnum.nextElement();
        Float nextPosition = (Float) positionEnum.nextElement();
        nextLayout.draw(graphics, nextPosition.floatValue(), verticalPos);
    }

    verticalPos = maxDescent;
}

}

The LineBreakMeasurer class allows styled text to be
broken into lines (or segments) that fit within a particular visual
advance.  This is useful for clients who wish to display a paragraph of
text that fits within a specific width, called the wrapping
width.

LineBreakMeasurer is constructed with an iterator over
styled text.  The iterator's range should be a single paragraph in the
text.
LineBreakMeasurer maintains a position in the text for the
start of the next text segment.  Initially, this position is the
start of text.  Paragraphs are assigned an overall direction (either
left-to-right or right-to-left) according to the bidirectional
formatting rules.  All segments obtained from a paragraph have the
same direction as the paragraph.

Segments of text are obtained by calling the method
nextLayout, which returns a TextLayout
representing the text that fits within the wrapping width.
The nextLayout method moves the current position
to the end of the layout returned from nextLayout.

LineBreakMeasurer implements the most commonly used
line-breaking policy: Every word that fits within the wrapping
width is placed on the line. If the first word does not fit, then all
of the characters that fit within the wrapping width are placed on the
line.  At least one character is placed on each line.

The TextLayout instances returned by
LineBreakMeasurer treat tabs like 0-width spaces.  Clients
who wish to obtain tab-delimited segments for positioning should use
the overload of nextLayout which takes a limiting offset
in the text.
The limiting offset should be the first character after the tab.
The TextLayout objects returned from this method end
at the limit provided (or before, if the text between the current
position and the limit won't fit entirely within the  wrapping
width).

Clients who are laying out tab-delimited text need a slightly
different line-breaking policy after the first segment has been
placed on a line.  Instead of fitting partial words in the
remaining space, they should place words which don't fit in the
remaining space entirely on the next line.  This change of policy
can be requested in the overload of nextLayout which
takes a boolean parameter.  If this parameter is
true, nextLayout returns
null if the first word won't fit in
the given space.  See the tab sample below.

In general, if the text used to construct the
LineBreakMeasurer changes, a new
LineBreakMeasurer must be constructed to reflect
the change.  (The old LineBreakMeasurer continues to
function properly, but it won't be aware of the text change.)
Nevertheless, if the text change is the insertion or deletion of a
single character, an existing LineBreakMeasurer can be
'updated' by calling insertChar or
deleteChar. Updating an existing
LineBreakMeasurer is much faster than creating a new one.
Clients who modify text based on user typing should take advantage
of these methods.

Examples:
Rendering a paragraph in a component



public void paint(Graphics graphics) {

    Point2D pen = new Point2D(10, 20);
    Graphics2D g2d = (Graphics2D)graphics;
    FontRenderContext frc = g2d.getFontRenderContext();

    // let styledText be an AttributedCharacterIterator containing at least
    // one character

    LineBreakMeasurer measurer = new LineBreakMeasurer(styledText, frc);
    float wrappingWidth = getSize().width - 15;

    while (measurer.getPosition() < fStyledText.length()) {

        TextLayout layout = measurer.nextLayout(wrappingWidth);

        pen.y = (layout.getAscent());
        float dx = layout.isLeftToRight() ?
            0 : (wrappingWidth - layout.getAdvance());

        layout.draw(graphics, pen.x  dx, pen.y);
        pen.y = layout.getDescent()  layout.getLeading();
    }
}


Rendering text with tabs.  For simplicity, the overall text
direction is assumed to be left-to-right



public void paint(Graphics graphics) {

    float leftMargin = 10, rightMargin = 310;
    float[] tabStops = { 100, 250 };

    // assume styledText is an AttributedCharacterIterator, and the number
    // of tabs in styledText is tabCount

    int[] tabLocations = new int[tabCount+1];

    int i = 0;
    for (char c = styledText.first(); c != styledText.DONE; c = styledText.next()) {
        if (c == '\t') {
            tabLocations[i++] = styledText.getIndex();
        }
    }
    tabLocations[tabCount] = styledText.getEndIndex() - 1;

    // Now tabLocations has an entry for every tab's offset in
    // the text.  For convenience, the last entry is tabLocations
    // is the offset of the last character in the text.

    LineBreakMeasurer measurer = new LineBreakMeasurer(styledText);
    int currentTab = 0;
    float verticalPos = 20;

    while (measurer.getPosition() < styledText.getEndIndex()) {

        // Lay out and draw each line.  All segments on a line
        // must be computed before any drawing can occur, since
        // we must know the largest ascent on the line.
        // TextLayouts are computed and stored in a Vector;
        // their horizontal positions are stored in a parallel
        // Vector.

        // lineContainsText is true after first segment is drawn
        boolean lineContainsText = false;
        boolean lineComplete = false;
        float maxAscent = 0, maxDescent = 0;
        float horizontalPos = leftMargin;
        Vector layouts = new Vector(1);
        Vector penPositions = new Vector(1);

        while (!lineComplete) {
            float wrappingWidth = rightMargin - horizontalPos;
            TextLayout layout =
                    measurer.nextLayout(wrappingWidth,
                                        tabLocations[currentTab]+1,
                                        lineContainsText);

            // layout can be null if lineContainsText is true
            if (layout != null) {
                layouts.addElement(layout);
                penPositions.addElement(new Float(horizontalPos));
                horizontalPos = layout.getAdvance();
                maxAscent = Math.max(maxAscent, layout.getAscent());
                maxDescent = Math.max(maxDescent,
                    layout.getDescent()  layout.getLeading());
            } else {
                lineComplete = true;
            }

            lineContainsText = true;

            if (measurer.getPosition() == tabLocations[currentTab]+1) {
                currentTab++;
            }

            if (measurer.getPosition() == styledText.getEndIndex())
                lineComplete = true;
            else if (horizontalPos >= tabStops[tabStops.length-1])
                lineComplete = true;

            if (!lineComplete) {
                // move to next tab stop
                int j;
                for (j=0; horizontalPos >= tabStops[j]; j++) {}
                horizontalPos = tabStops[j];
            }
        }

        verticalPos = maxAscent;

        Enumeration layoutEnum = layouts.elements();
        Enumeration positionEnum = penPositions.elements();

        // now iterate through layouts and draw them
        while (layoutEnum.hasMoreElements()) {
            TextLayout nextLayout = (TextLayout) layoutEnum.nextElement();
            Float nextPosition = (Float) positionEnum.nextElement();
            nextLayout.draw(graphics, nextPosition.floatValue(), verticalPos);
        }

        verticalPos = maxDescent;
    }
}
raw docstring

jdk.awt.font.LineMetrics

The LineMetrics class allows access to the metrics needed to layout characters along a line and to layout of a set of lines. A LineMetrics object encapsulates the measurement information associated with a run of text.

Fonts can have different metrics for different ranges of characters. The getLineMetrics methods of Font take some text as an argument and return a LineMetrics object describing the metrics of the initial number of characters in that text, as returned by getNumChars().

The LineMetrics class allows access to the
metrics needed to layout characters along a line
and to layout of a set of lines.  A LineMetrics
object encapsulates the measurement information associated
with a run of text.

Fonts can have different metrics for different ranges of
characters.  The getLineMetrics methods of
Font take some text as an argument
and return a LineMetrics object describing the
metrics of the initial number of characters in that text, as
returned by getNumChars().
raw docstring

jdk.awt.font.MultipleMaster

The MultipleMaster interface represents Type 1 Multiple Master fonts. A particular Font object can implement this interface.

The MultipleMaster interface represents Type 1
Multiple Master fonts.
A particular Font object can implement this interface.
raw docstring

jdk.awt.font.NumericShaper

The NumericShaper class is used to convert Latin-1 (European) digits to other Unicode decimal digits. Users of this class will primarily be people who wish to present data using national digit shapes, but find it more convenient to represent the data internally using Latin-1 (European) digits. This does not interpret the deprecated numeric shape selector character (U+206E).

Instances of NumericShaper are typically applied as attributes to text with the NUMERIC_SHAPING attribute of the TextAttribute class. For example, this code snippet causes a TextLayout to shape European digits to Arabic in an Arabic context:

Map map = new HashMap(); map.put(TextAttribute.NUMERIC_SHAPING, NumericShaper.getContextualShaper(NumericShaper.ARABIC)); FontRenderContext frc = ...; TextLayout layout = new TextLayout(text, map, frc); layout.draw(g2d, x, y);

It is also possible to perform numeric shaping explicitly using instances of NumericShaper, as this code snippet demonstrates:

char[] text = ...; // shape all EUROPEAN digits (except zero) to ARABIC digits NumericShaper shaper = NumericShaper.getShaper(NumericShaper.ARABIC); shaper.shape(text, start, count);

// shape European digits to ARABIC digits if preceding text is Arabic, or // shape European digits to TAMIL digits if preceding text is Tamil, or // leave European digits alone if there is no preceding text, or // preceding text is neither Arabic nor Tamil NumericShaper shaper = NumericShaper.getContextualShaper(NumericShaper.ARABIC | NumericShaper.TAMIL, NumericShaper.EUROPEAN); shaper.shape(text, start, count);

Bit mask- and enum-based Unicode ranges

This class supports two different programming interfaces to represent Unicode ranges for script-specific digits: bit mask-based ones, such as NumericShaper.ARABIC, and enum-based ones, such as NumericShaper.Range.ARABIC. Multiple ranges can be specified by ORing bit mask-based constants, such as:

NumericShaper.ARABIC | NumericShaper.TAMIL or creating a Set with the NumericShaper.Range constants, such as:

EnumSet.of(NumericShaper.Scirpt.ARABIC, NumericShaper.Range.TAMIL) The enum-based ranges are a super set of the bit mask-based ones.

If the two interfaces are mixed (including serialization), Unicode range values are mapped to their counterparts where such mapping is possible, such as NumericShaper.Range.ARABIC from/to NumericShaper.ARABIC. If any unmappable range values are specified, such as NumericShaper.Range.BALINESE, those ranges are ignored.

Decimal Digits Precedence

A Unicode range may have more than one set of decimal digits. If multiple decimal digits sets are specified for the same Unicode range, one of the sets will take precedence as follows.

  Unicode Range
  NumericShaper Constants
  Precedence


  Arabic
  NumericShaper.ARABIC
      NumericShaper.EASTERN_ARABIC
  NumericShaper.EASTERN_ARABIC


  NumericShaper.Range.ARABIC
      NumericShaper.Range.EASTERN_ARABIC
  NumericShaper.Range.EASTERN_ARABIC


  Tai Tham
  NumericShaper.Range.TAI_THAM_HORA
      NumericShaper.Range.TAI_THAM_THAM
  NumericShaper.Range.TAI_THAM_THAM
The NumericShaper class is used to convert Latin-1 (European)
digits to other Unicode decimal digits.  Users of this class will
primarily be people who wish to present data using
national digit shapes, but find it more convenient to represent the
data internally using Latin-1 (European) digits.  This does not
interpret the deprecated numeric shape selector character (U+206E).

Instances of NumericShaper are typically applied
as attributes to text with the
NUMERIC_SHAPING attribute
of the TextAttribute class.
For example, this code snippet causes a TextLayout to
shape European digits to Arabic in an Arabic context:


Map map = new HashMap();
map.put(TextAttribute.NUMERIC_SHAPING,
    NumericShaper.getContextualShaper(NumericShaper.ARABIC));
FontRenderContext frc = ...;
TextLayout layout = new TextLayout(text, map, frc);
layout.draw(g2d, x, y);

It is also possible to perform numeric shaping explicitly using instances
of NumericShaper, as this code snippet demonstrates:


char[] text = ...;
// shape all EUROPEAN digits (except zero) to ARABIC digits
NumericShaper shaper = NumericShaper.getShaper(NumericShaper.ARABIC);
shaper.shape(text, start, count);

// shape European digits to ARABIC digits if preceding text is Arabic, or
// shape European digits to TAMIL digits if preceding text is Tamil, or
// leave European digits alone if there is no preceding text, or
// preceding text is neither Arabic nor Tamil
NumericShaper shaper =
    NumericShaper.getContextualShaper(NumericShaper.ARABIC |
                                        NumericShaper.TAMIL,
                                      NumericShaper.EUROPEAN);
shaper.shape(text, start, count);

Bit mask- and enum-based Unicode ranges

This class supports two different programming interfaces to
represent Unicode ranges for script-specific digits: bit
mask-based ones, such as NumericShaper.ARABIC, and
enum-based ones, such as NumericShaper.Range.ARABIC.
Multiple ranges can be specified by ORing bit mask-based constants,
such as:


NumericShaper.ARABIC | NumericShaper.TAMIL
or creating a Set with the NumericShaper.Range
constants, such as:


EnumSet.of(NumericShaper.Scirpt.ARABIC, NumericShaper.Range.TAMIL)
The enum-based ranges are a super set of the bit mask-based ones.

If the two interfaces are mixed (including serialization),
Unicode range values are mapped to their counterparts where such
mapping is possible, such as NumericShaper.Range.ARABIC
from/to NumericShaper.ARABIC.  If any unmappable range
values are specified, such as NumericShaper.Range.BALINESE,
those ranges are ignored.

Decimal Digits Precedence

A Unicode range may have more than one set of decimal digits. If
multiple decimal digits sets are specified for the same Unicode
range, one of the sets will take precedence as follows.



      Unicode Range
      NumericShaper Constants
      Precedence


      Arabic
      NumericShaper.ARABIC
          NumericShaper.EASTERN_ARABIC
      NumericShaper.EASTERN_ARABIC


      NumericShaper.Range.ARABIC
          NumericShaper.Range.EASTERN_ARABIC
      NumericShaper.Range.EASTERN_ARABIC


      Tai Tham
      NumericShaper.Range.TAI_THAM_HORA
          NumericShaper.Range.TAI_THAM_THAM
      NumericShaper.Range.TAI_THAM_THAM
raw docstring

jdk.awt.font.OpenType

The OpenType interface represents OpenType and TrueType fonts. This interface makes it possible to obtain sfnt tables from the font. A particular Font object can implement this interface.

For more information on TrueType and OpenType fonts, see the OpenType specification. ( http://www.microsoft.com/typography/otspec/ ).

The OpenType interface represents OpenType and
TrueType fonts.  This interface makes it possible to obtain
sfnt tables from the font.  A particular
Font object can implement this interface.

For more information on TrueType and OpenType fonts, see the
OpenType specification.
( http://www.microsoft.com/typography/otspec/ ).
raw docstring

jdk.awt.font.ShapeGraphicAttribute

The ShapeGraphicAttribute class is an implementation of GraphicAttribute that draws shapes in a TextLayout.

The ShapeGraphicAttribute class is an implementation of
GraphicAttribute that draws shapes in a TextLayout.
raw docstring

jdk.awt.font.TextAttribute

The TextAttribute class defines attribute keys and attribute values used for text rendering.

TextAttribute instances are used as attribute keys to identify attributes in Font, TextLayout, AttributedCharacterIterator, and other classes handling text attributes. Other constants defined in this class can be used as attribute values.

For each text attribute, the documentation provides:

the type of its value, the relevant predefined constants, if any the default effect if the attribute is absent the valid values if there are limitations a description of the effect.

Values

The values of attributes must always be immutable. Where value limitations are given, any value outside of that set is reserved for future use; the value will be treated as the default. The value null is treated the same as the default value and results in the default behavior. If the value is not of the proper type, the attribute will be ignored. The identity of the value does not matter, only the actual value. For example, TextAttribute.WEIGHT_BOLD and new Float(2.0) indicate the same WEIGHT. Attribute values of type Number (used for WEIGHT, WIDTH, POSTURE, SIZE, JUSTIFICATION, and TRACKING) can vary along their natural range and are not restricted to the predefined constants. Number.floatValue() is used to get the actual value from the Number. The values for WEIGHT, WIDTH, and POSTURE are interpolated by the system, which can select the 'nearest available' font or use other techniques to approximate the user's request.

Summary of attributes

Key Value Type Principal Constants Default Value

FAMILY String See Font DIALOG, DIALOG_INPUT, SERIF, SANS_SERIF, and MONOSPACED.

"Default" (use platform default)

WEIGHT Number WEIGHT_REGULAR, WEIGHT_BOLD WEIGHT_REGULAR

WIDTH Number WIDTH_CONDENSED, WIDTH_REGULAR,WIDTH_EXTENDED WIDTH_REGULAR

POSTURE Number POSTURE_REGULAR, POSTURE_OBLIQUE POSTURE_REGULAR

SIZE Number none 12.0

TRANSFORM TransformAttribute See TransformAttribute IDENTITY TransformAttribute.IDENTITY

SUPERSCRIPT Integer SUPERSCRIPT_SUPER, SUPERSCRIPT_SUB 0 (use the standard glyphs and metrics)

FONT Font none null (do not override font resolution)

CHAR_REPLACEMENT GraphicAttribute none null (draw text using font glyphs)

FOREGROUND Paint none null (use current graphics paint)

BACKGROUND Paint none null (do not render background)

UNDERLINE Integer UNDERLINE_ON -1 (do not render underline)

STRIKETHROUGH Boolean STRIKETHROUGH_ON false (do not render strikethrough)

RUN_DIRECTION Boolean RUN_DIRECTION_LTRRUN_DIRECTION_RTL null (use Bidi standard default)

BIDI_EMBEDDING Integer none 0 (use base line direction)

JUSTIFICATION Number JUSTIFICATION_FULL JUSTIFICATION_FULL

INPUT_METHOD_HIGHLIGHT InputMethodHighlight,Annotation (see class) null (do not apply input highlighting)

INPUT_METHOD_UNDERLINE Integer UNDERLINE_LOW_ONE_PIXEL,UNDERLINE_LOW_TWO_PIXEL -1 (do not render underline)

SWAP_COLORS Boolean SWAP_COLORS_ON false (do not swap colors)

NUMERIC_SHAPING NumericShaper none null (do not shape digits)

KERNING Integer KERNING_ON 0 (do not request kerning)

LIGATURES Integer LIGATURES_ON 0 (do not form optional ligatures)

TRACKING Number TRACKING_LOOSE, TRACKING_TIGHT 0 (do not add tracking)

The TextAttribute class defines attribute keys and
attribute values used for text rendering.

TextAttribute instances are used as attribute keys to
identify attributes in
Font,
TextLayout,
AttributedCharacterIterator,
and other classes handling text attributes. Other constants defined
in this class can be used as attribute values.

For each text attribute, the documentation provides:

  the type of its value,
  the relevant predefined constants, if any
  the default effect if the attribute is absent
  the valid values if there are limitations
  a description of the effect.


Values

  The values of attributes must always be immutable.
  Where value limitations are given, any value outside of that
  set is reserved for future use; the value will be treated as
  the default.
  The value null is treated the same as the
  default value and results in the default behavior.
  If the value is not of the proper type, the attribute
  will be ignored.
  The identity of the value does not matter, only the actual
  value.  For example, TextAttribute.WEIGHT_BOLD and
  new Float(2.0)
  indicate the same WEIGHT.
  Attribute values of type Number (used for
  WEIGHT, WIDTH, POSTURE,
  SIZE, JUSTIFICATION, and
  TRACKING) can vary along their natural range and are
  not restricted to the predefined constants.
  Number.floatValue() is used to get the actual value
  from the Number.
  The values for WEIGHT, WIDTH, and
  POSTURE are interpolated by the system, which
  can select the 'nearest available' font or use other techniques to
  approximate the user's request.



Summary of attributes



Key
Value Type
Principal Constants
Default Value


FAMILY
String
See Font DIALOG,
DIALOG_INPUT, SERIF,
SANS_SERIF, and MONOSPACED.

"Default" (use platform default)


WEIGHT
Number
WEIGHT_REGULAR, WEIGHT_BOLD
WEIGHT_REGULAR


WIDTH
Number
WIDTH_CONDENSED, WIDTH_REGULAR,WIDTH_EXTENDED
WIDTH_REGULAR


POSTURE
Number
POSTURE_REGULAR, POSTURE_OBLIQUE
POSTURE_REGULAR


SIZE
Number
none
12.0


TRANSFORM
TransformAttribute
See TransformAttribute IDENTITY
TransformAttribute.IDENTITY


SUPERSCRIPT
Integer
SUPERSCRIPT_SUPER, SUPERSCRIPT_SUB
0 (use the standard glyphs and metrics)


FONT
Font
none
null (do not override font resolution)


CHAR_REPLACEMENT
GraphicAttribute
none
null (draw text using font glyphs)


FOREGROUND
Paint
none
null (use current graphics paint)


BACKGROUND
Paint
none
null (do not render background)


UNDERLINE
Integer
UNDERLINE_ON
-1 (do not render underline)


STRIKETHROUGH
Boolean
STRIKETHROUGH_ON
false (do not render strikethrough)


RUN_DIRECTION
Boolean
RUN_DIRECTION_LTRRUN_DIRECTION_RTL
null (use Bidi standard default)


BIDI_EMBEDDING
Integer
none
0 (use base line direction)


JUSTIFICATION
Number
JUSTIFICATION_FULL
JUSTIFICATION_FULL


INPUT_METHOD_HIGHLIGHT
InputMethodHighlight,Annotation
(see class)
null (do not apply input highlighting)


INPUT_METHOD_UNDERLINE
Integer
UNDERLINE_LOW_ONE_PIXEL,UNDERLINE_LOW_TWO_PIXEL
-1 (do not render underline)


SWAP_COLORS
Boolean
SWAP_COLORS_ON
false (do not swap colors)


NUMERIC_SHAPING
NumericShaper
none
null (do not shape digits)


KERNING
Integer
KERNING_ON
0 (do not request kerning)


LIGATURES
Integer
LIGATURES_ON
0 (do not form optional ligatures)


TRACKING
Number
TRACKING_LOOSE, TRACKING_TIGHT
0 (do not add tracking)
raw docstring

jdk.awt.font.TextHitInfo

The TextHitInfo class represents a character position in a text model, and a bias, or "side," of the character. Biases are either leading (the left edge, for a left-to-right character) or trailing (the right edge, for a left-to-right character). Instances of TextHitInfo are used to specify caret and insertion positions within text.

For example, consider the text "abc". TextHitInfo.trailing(1) corresponds to the right side of the 'b' in the text.

TextHitInfo is used primarily by TextLayout and clients of TextLayout. Clients of TextLayout query TextHitInfo instances for an insertion offset, where new text is inserted into the text model. The insertion offset is equal to the character position in the TextHitInfo if the bias is leading, and one character after if the bias is trailing. The insertion offset for TextHitInfo.trailing(1) is 2.

Sometimes it is convenient to construct a TextHitInfo with the same insertion offset as an existing one, but on the opposite character. The getOtherHit method constructs a new TextHitInfo with the same insertion offset as an existing one, with a hit on the character on the other side of the insertion offset. Calling getOtherHit on trailing(1) would return leading(2). In general, getOtherHit for trailing(n) returns leading(n+1) and getOtherHit for leading(n) returns trailing(n-1).

Example: Converting a graphical point to an insertion point within a text model

TextLayout layout = ...; Point2D.Float hitPoint = ...; TextHitInfo hitInfo = layout.hitTestChar(hitPoint.x, hitPoint.y); int insPoint = hitInfo.getInsertionIndex(); // insPoint is relative to layout; may need to adjust for use // in a text model

The TextHitInfo class represents a character position in a
text model, and a bias, or "side," of the character.  Biases are
either leading (the left edge, for a left-to-right character)
or trailing (the right edge, for a left-to-right character).
Instances of TextHitInfo are used to specify caret and
insertion positions within text.

For example, consider the text "abc".  TextHitInfo.trailing(1)
corresponds to the right side of the 'b' in the text.

TextHitInfo is used primarily by TextLayout and
clients of TextLayout.  Clients of TextLayout
query TextHitInfo instances for an insertion offset, where
new text is inserted into the text model.  The insertion offset is equal
to the character position in the TextHitInfo if the bias
is leading, and one character after if the bias is trailing.  The
insertion offset for TextHitInfo.trailing(1) is 2.

Sometimes it is convenient to construct a TextHitInfo with
the same insertion offset as an existing one, but on the opposite
character.  The getOtherHit method constructs a new
TextHitInfo with the same insertion offset as an existing
one, with a hit on the character on the other side of the insertion offset.
Calling getOtherHit on trailing(1) would return leading(2).
In general, getOtherHit for trailing(n) returns
leading(n+1) and getOtherHit for leading(n)
returns trailing(n-1).

Example:
Converting a graphical point to an insertion point within a text
model


TextLayout layout = ...;
Point2D.Float hitPoint = ...;
TextHitInfo hitInfo = layout.hitTestChar(hitPoint.x, hitPoint.y);
int insPoint = hitInfo.getInsertionIndex();
// insPoint is relative to layout;  may need to adjust for use
// in a text model
raw docstring

jdk.awt.font.TextLayout

TextLayout is an immutable graphical representation of styled character data.

It provides the following capabilities:

implicit bidirectional analysis and reordering, cursor positioning and movement, including split cursors for mixed directional text, highlighting, including both logical and visual highlighting for mixed directional text, multiple baselines (roman, hanging, and centered), hit testing, justification, default font substitution, metric information such as ascent, descent, and advance, and rendering

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:

paragraph attributes are extracted and examined, text is analyzed for bidirectional reordering, and reordering information is computed if needed, text is segmented into style runs fonts are chosen for style runs, first by using a font if the attribute TextAttribute.FONT is present, otherwise by computing a default font using the attributes that have been defined if text is on multiple baselines, the runs or subruns are further broken into subruns sharing a common baseline, glyphvectors are generated for each run using the chosen font, final bidirectional reordering is performed on the glyphvectors

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

TextLayout is an immutable graphical representation of styled
character data.

It provides the following capabilities:

implicit bidirectional analysis and reordering,
cursor positioning and movement, including split cursors for
mixed directional text,
highlighting, including both logical and visual highlighting
for mixed directional text,
multiple baselines (roman, hanging, and centered),
hit testing,
justification,
default font substitution,
metric information such as ascent, descent, and advance, and
rendering


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:

paragraph attributes are extracted and examined,
text is analyzed for bidirectional reordering, and reordering
information is computed if needed,
text is segmented into style runs
fonts are chosen for style runs, first by using a font if the
attribute TextAttribute.FONT is present, otherwise by computing
a default font using the attributes that have been defined
if text is on multiple baselines, the runs or subruns are further
broken into subruns sharing a common baseline,
glyphvectors are generated for each run using the chosen font,
final bidirectional reordering is performed on the glyphvectors


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 tranlated 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.
raw docstring

jdk.awt.font.TextLayout$CaretPolicy

Defines a policy for determining the strong caret location. This class contains one method, getStrongCaret, which is used to specify the policy that determines the strong caret in dual-caret text. The strong caret is used to move the caret to the left or right. Instances of this class can be passed to getCaretShapes, getNextLeftHit and getNextRightHit to customize strong caret selection.

To specify alternate caret policies, subclass CaretPolicy and override getStrongCaret. getStrongCaret should inspect the two TextHitInfo arguments and choose one of them as the strong caret.

Most clients do not need to use this class.

Defines a policy for determining the strong caret location.
This class contains one method, getStrongCaret, which
is used to specify the policy that determines the strong caret in
dual-caret text.  The strong caret is used to move the caret to the
left or right. Instances of this class can be passed to
getCaretShapes, getNextLeftHit and
getNextRightHit to customize strong caret
selection.

To specify alternate caret policies, subclass CaretPolicy
and override getStrongCaret.  getStrongCaret
should inspect the two TextHitInfo arguments and choose
one of them as the strong caret.

Most clients do not need to use this class.
raw docstring

jdk.awt.font.TextMeasurer

The TextMeasurer class provides the primitive operations needed for line break: measuring up to a given advance, determining the advance of a range of characters, and generating a TextLayout for a range of characters. It also provides methods for incremental editing of paragraphs.

A TextMeasurer object is constructed with an AttributedCharacterIterator representing a single paragraph of text. The value returned by the getBeginIndex method of AttributedCharacterIterator defines the absolute index of the first character. The value returned by the getEndIndex method of AttributedCharacterIterator defines the index past the last character. These values define the range of indexes to use in calls to the TextMeasurer. For example, calls to get the advance of a range of text or the line break of a range of text must use indexes between the beginning and end index values. Calls to insertChar and deleteChar reset the TextMeasurer to use the beginning index and end index of the AttributedCharacterIterator passed in those calls.

Most clients will use the more convenient LineBreakMeasurer, which implements the standard line break policy (placing as many words as will fit on each line).

The TextMeasurer class provides the primitive operations
needed for line break: measuring up to a given advance, determining the
advance of a range of characters, and generating a
TextLayout for a range of characters. It also provides
methods for incremental editing of paragraphs.

A TextMeasurer object is constructed with an
AttributedCharacterIterator
representing a single paragraph of text.  The value returned by the
getBeginIndex
method of AttributedCharacterIterator
defines the absolute index of the first character.  The value
returned by the
getEndIndex
method of AttributedCharacterIterator defines the index
past the last character.  These values define the range of indexes to
use in calls to the TextMeasurer.  For example, calls to
get the advance of a range of text or the line break of a range of text
must use indexes between the beginning and end index values.  Calls to
insertChar
and
deleteChar
reset the TextMeasurer to use the beginning index and end
index of the AttributedCharacterIterator passed in those calls.

Most clients will use the more convenient LineBreakMeasurer,
which implements the standard line break policy (placing as many words
as will fit on each line).
raw docstring

jdk.awt.font.TransformAttribute

The TransformAttribute class provides an immutable wrapper for a transform so that it is safe to use as an attribute.

The TransformAttribute class provides an immutable
wrapper for a transform so that it is safe to use as an attribute.
raw docstring

cljdoc is a website building & hosting documentation for Clojure/Script libraries

× close