Example usage for java.awt.font LineBreakMeasurer LineBreakMeasurer

List of usage examples for java.awt.font LineBreakMeasurer LineBreakMeasurer

Introduction

In this page you can find the example usage for java.awt.font LineBreakMeasurer LineBreakMeasurer.

Prototype

public LineBreakMeasurer(AttributedCharacterIterator text, FontRenderContext frc) 

Source Link

Document

Constructs a LineBreakMeasurer for the specified text.

Usage

From source file:LineBreakSample.java

public LineBreakSample() {
    AttributedCharacterIterator paragraph = vanGogh.getIterator();
    paragraphStart = paragraph.getBeginIndex();
    paragraphEnd = paragraph.getEndIndex();

    // Create a new LineBreakMeasurer from the paragraph.
    lineMeasurer = new LineBreakMeasurer(paragraph, new FontRenderContext(null, false, false));
}

From source file:MainClass.java

private void getLayouts(Graphics g) {
    layouts = new ArrayList();

    Graphics2D g2d = (Graphics2D) g;
    FontRenderContext frc = g2d.getFontRenderContext();

    AttributedString attrStr = new AttributedString(text);
    attrStr.addAttribute(TextAttribute.FONT, font, 0, text.length());
    LineBreakMeasurer measurer = new LineBreakMeasurer(attrStr.getIterator(), frc);
    float wrappingWidth;

    wrappingWidth = getSize().width - 15;

    while (measurer.getPosition() < text.length()) {
        TextLayout layout = measurer.nextLayout(wrappingWidth);
        layouts.add(layout);//from   ww  w.  j  a  v a 2 s. co  m
    }
}

From source file:Main.java

/**
 * Returns the {@link Dimension} for the given {@link JTextComponent}
 * subclass that will show the whole word wrapped text in the given width.
 * It won't work for styled text of varied size or style, it's assumed that
 * the whole text is rendered with the {@link JTextComponent}s font.
 *
 * @param textComponent the {@link JTextComponent} to calculate the {@link Dimension} for
 * @param width the width of the resulting {@link Dimension}
 * @param text the {@link String} which should be word wrapped
 * @return The calculated {@link Dimension}
 *///w w w  .  j av a 2  s  .co m
public static Dimension getWordWrappedTextDimension(JTextComponent textComponent, int width, String text) {
    if (textComponent == null) {
        throw new IllegalArgumentException("textComponent cannot be null");
    }
    if (width < 1) {
        throw new IllegalArgumentException("width must be 1 or greater");
    }
    if (text == null) {
        text = textComponent.getText();
    }
    if (text.isEmpty()) {
        return new Dimension(width, 0);
    }

    FontMetrics metrics = textComponent.getFontMetrics(textComponent.getFont());
    FontRenderContext rendererContext = metrics.getFontRenderContext();
    float formatWidth = width - textComponent.getInsets().left - textComponent.getInsets().right;

    int lines = 0;
    String[] paragraphs = text.split("\n");
    for (String paragraph : paragraphs) {
        if (paragraph.isEmpty()) {
            lines++;
        } else {
            AttributedString attributedText = new AttributedString(paragraph);
            attributedText.addAttribute(TextAttribute.FONT, textComponent.getFont());
            AttributedCharacterIterator charIterator = attributedText.getIterator();
            LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(charIterator, rendererContext);

            lineMeasurer.setPosition(charIterator.getBeginIndex());
            while (lineMeasurer.getPosition() < charIterator.getEndIndex()) {
                lineMeasurer.nextLayout(formatWidth);
                lines++;
            }
        }
    }

    return new Dimension(width,
            metrics.getHeight() * lines + textComponent.getInsets().top + textComponent.getInsets().bottom);
}

From source file:Utils.java

/** 
 * Renders a paragraph of text (line breaks ignored) to an image (created and returned). 
 *
 * @param font The font to use/*from w w  w  .  j a v a2 s .c o m*/
 * @param textColor The color of the text
 * @param text The message
 * @param width The width the text should be limited to
 * @return An image with the text rendered into it
 */
public static BufferedImage renderTextToImage(Font font, Color textColor, String text, int width) {
    Hashtable map = new Hashtable();
    map.put(TextAttribute.FONT, font);
    AttributedString attributedString = new AttributedString(text, map);
    AttributedCharacterIterator paragraph = attributedString.getIterator();

    FontRenderContext frc = new FontRenderContext(null, false, false);
    int paragraphStart = paragraph.getBeginIndex();
    int paragraphEnd = paragraph.getEndIndex();
    LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(paragraph, frc);

    float drawPosY = 0;

    //First time around, just determine the height
    while (lineMeasurer.getPosition() < paragraphEnd) {
        TextLayout layout = lineMeasurer.nextLayout(width);

        // Move it down
        drawPosY += layout.getAscent() + layout.getDescent() + layout.getLeading();
    }

    BufferedImage image = createCompatibleImage(width, (int) drawPosY);
    Graphics2D graphics = (Graphics2D) image.getGraphics();
    graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

    drawPosY = 0;
    lineMeasurer.setPosition(paragraphStart);
    while (lineMeasurer.getPosition() < paragraphEnd) {
        TextLayout layout = lineMeasurer.nextLayout(width);

        // Move y-coordinate by the ascent of the layout.
        drawPosY += layout.getAscent();

        /* Compute pen x position.  If the paragraph is
           right-to-left, we want to align the TextLayouts
           to the right edge of the panel.
         */
        float drawPosX;
        if (layout.isLeftToRight()) {
            drawPosX = 0;
        } else {
            drawPosX = width - layout.getAdvance();
        }

        // Draw the TextLayout at (drawPosX, drawPosY).
        layout.draw(graphics, drawPosX, drawPosY);

        // Move y-coordinate in preparation for next layout.
        drawPosY += layout.getDescent() + layout.getLeading();
    }

    graphics.dispose();
    return image;
}

From source file:com.sander.verhagen.frame.LineWrapCellRenderer.java

private int getLineCount(JTextArea textArea) {
    AttributedString string = new AttributedString(textArea.getText());
    FontRenderContext fontRenderContext = textArea.getFontMetrics(textArea.getFont()).getFontRenderContext();
    AttributedCharacterIterator characterIterator = string.getIterator();
    LineBreakMeasurer lineBreakMeasurer = new LineBreakMeasurer(characterIterator, fontRenderContext);
    lineBreakMeasurer.setPosition(characterIterator.getBeginIndex());

    int lineCount = 0;
    while (lineBreakMeasurer.getPosition() < characterIterator.getEndIndex()) {
        lineBreakMeasurer.nextLayout(textArea.getSize().width);
        lineCount++;/*from   w w  w.  j av  a 2 s  . c o  m*/
    }
    return lineCount;
}

From source file:TextFormat.java

/**
 * Lazy evaluation of the List of TextLayout objects corresponding to this
 * MText. Some things are approximations!
 *///  w w  w  .java 2 s .c om
private void getLayouts(Graphics g) {
    layouts = new ArrayList();

    Point pen = new Point(10, 20);
    Graphics2D g2d = (Graphics2D) g;
    FontRenderContext frc = g2d.getFontRenderContext();

    AttributedString attrStr = new AttributedString(text);
    attrStr.addAttribute(TextAttribute.FONT, font, 0, text.length());
    LineBreakMeasurer measurer = new LineBreakMeasurer(attrStr.getIterator(), frc);
    float wrappingWidth;

    wrappingWidth = getSize().width - 15;

    while (measurer.getPosition() < text.length()) {
        TextLayout layout = measurer.nextLayout(wrappingWidth);
        layouts.add(layout);
    }
}

From source file:com.pronoiahealth.olhie.server.services.BookCoverImageService.java

/**
 * Create an image that contains text//from   w  ww .ja va  2s . co m
 * 
 * @param height
 * @param width
 * @param text
 * @param textColor
 * @param center
 * @param fontMap
 * @param type
 * @return
 */
private BufferedImage createText(int height, int width, String text, String textColor, boolean center,
        Map<TextAttribute, Object> fontMap, int type) {
    BufferedImage img = new BufferedImage(width, height, type);
    Graphics2D g2d = null;
    try {
        g2d = (Graphics2D) img.getGraphics();

        // Create attributed text
        AttributedString txt = new AttributedString(text, fontMap);

        // Set graphics color
        g2d.setColor(Color.decode(textColor));

        // Create a new LineBreakMeasurer from the paragraph.
        // It will be cached and re-used.
        AttributedCharacterIterator paragraph = txt.getIterator();
        int paragraphStart = paragraph.getBeginIndex();
        int paragraphEnd = paragraph.getEndIndex();
        FontRenderContext frc = g2d.getFontRenderContext();
        LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(paragraph, frc);

        // Set break width to width of Component.
        float breakWidth = (float) width;
        float drawPosY = 0;
        // Set position to the index of the first character in the
        // paragraph.
        lineMeasurer.setPosition(paragraphStart);

        // Get lines until the entire paragraph has been displayed.
        while (lineMeasurer.getPosition() < paragraphEnd) {
            // Retrieve next layout. A cleverer program would also cache
            // these layouts until the component is re-sized.
            TextLayout layout = lineMeasurer.nextLayout(breakWidth);

            // Compute pen x position. If the paragraph is right-to-left we
            // will align the TextLayouts to the right edge of the panel.
            // Note: drawPosX is always where the LEFT of the text is
            // placed.
            float drawPosX = layout.isLeftToRight() ? 0 : breakWidth - layout.getAdvance();

            if (center == true) {
                double xOffSet = (width - layout.getBounds().getWidth()) / 2;
                drawPosX = drawPosX + new Float(xOffSet);
            }

            // Move y-coordinate by the ascent of the layout.
            drawPosY += layout.getAscent();

            // Draw the TextLayout at (drawPosX, drawPosY).
            layout.draw(g2d, drawPosX, drawPosY);

            // Move y-coordinate in preparation for next layout.
            drawPosY += layout.getDescent() + layout.getLeading();
        }
    } finally {
        if (g2d != null) {
            g2d.dispose();
        }
    }
    return img;
}

From source file:com.lfv.lanzius.server.WorkspaceView.java

@Override
protected void paintComponent(Graphics g) {
    int w = getWidth();
    int h = getHeight();

    Document doc = server.getDocument();

    Color storedCol = g.getColor();
    Font storedFont = g.getFont();

    // Fill workspace area
    g.setColor(getBackground());/*from  w  w  w. ja v a2s. c  o m*/
    g.fillRect(0, 0, w, h);

    // Should the cached version be updated?
    int updateDocumentVersion = server.getDocumentVersion();
    boolean update = (documentVersion != updateDocumentVersion);

    // Check if we have cached the latest document version, otherwise cache the terminals
    if (update) {
        log.debug("Updating view to version " + updateDocumentVersion);
        terminalMap.clear();
        groupList.clear();
        if (doc != null) {
            synchronized (doc) {

                // Clear the visible attribute on all groups
                // except the started or paused ones
                Element egd = doc.getRootElement().getChild("GroupDefs");
                Iterator iter = egd.getChildren().iterator();
                while (iter.hasNext()) {
                    Element eg = (Element) iter.next();
                    boolean isVisible = !DomTools.getAttributeString(eg, "state", "stopped", false)
                            .equals("stopped");
                    eg.setAttribute("visible", String.valueOf(isVisible));
                }

                // Gather information about terminals and cache it
                Element etd = doc.getRootElement().getChild("TerminalDefs");
                iter = etd.getChildren().iterator();
                while (iter.hasNext()) {
                    Element et = (Element) iter.next();
                    int tid = DomTools.getAttributeInt(et, "id", 0, false);
                    if (tid > 0) {
                        // Create terminal and add it to list
                        Terminal t = new Terminal(tid, DomTools.getAttributeInt(et, "x", 0, false),
                                DomTools.getAttributeInt(et, "y", 0, false),
                                DomTools.getChildText(et, "Name", "T/" + tid, false),
                                DomTools.getAttributeBoolean(et, "online", false, false),
                                DomTools.getAttributeBoolean(et, "selected", false, false));
                        terminalMap.put(tid, t);

                        // Is the terminal monitored?
                        t.isMonitored = DomTools.getAttributeBoolean(et, "monitored", false, false);

                        // Examine the Player element under PlayerSetup
                        t.groupColor = null;
                        Element ep = DomTools.getElementFromSection(doc, "PlayerSetup", "terminalid",
                                String.valueOf(tid));

                        // Has linked player for this terminal
                        if (ep != null) {
                            StringBuffer sb = new StringBuffer();

                            // Append player name
                            sb.append(DomTools.getChildText(ep, "Name", "P/?", true));
                            sb.append(" (");

                            // Append role list
                            boolean hasRoles = false;
                            Element ers = ep.getChild("RoleSetup");
                            if (ers != null) {
                                Iterator iterr = ers.getChildren().iterator();

                                while (iterr.hasNext()) {
                                    Element er = (Element) iterr.next();
                                    String id = er.getAttributeValue("id");
                                    er = DomTools.getElementFromSection(doc, "RoleDefs", "id", id);
                                    if (er != null) {
                                        sb.append(DomTools.getChildText(er, "Name", "R/" + id, false));
                                        sb.append(", ");
                                        hasRoles = true;
                                    }
                                }
                                if (hasRoles) {
                                    // Trim last comma
                                    int len = sb.length();
                                    sb.setLength(Math.max(len - 2, 0));
                                }
                                sb.append(")");
                            }
                            t.roles = sb.toString();

                            // Is the player relocated?
                            t.isRelocated = DomTools.getAttributeBoolean(ep, "relocated", false, false);

                            // Get group name and color
                            Element eg = DomTools.getElementFromSection(doc, "GroupDefs", "id",
                                    DomTools.getAttributeString(ep, "groupid", "0", true));
                            t.groupColor = Color.lightGray;
                            if (eg != null) {
                                String sc = DomTools.getChildText(eg, "Color", null, false);
                                if (sc != null) {
                                    try {
                                        t.groupColor = Color.decode(sc);
                                    } catch (NumberFormatException ex) {
                                        log.warn("Invalid color attribute on Group node, defaulting to grey");
                                    }
                                }
                                //t.name += "  "+DomTools.getChildText(eg, "Name", "G/"+eg.getAttributeValue("id"), false);
                                t.groupName = DomTools.getChildText(eg, "Name",
                                        "G/" + eg.getAttributeValue("id"), false);

                                // This group should now be visible
                                eg.setAttribute("visible", "true");
                            } else
                                log.warn("Invalid groupid attribute on Player node, defaulting to grey");
                        }
                    } else
                        log.error("Invalid id attribute on Terminal node, skipping");
                }

                // Gather information about groups and cache it
                iter = egd.getChildren().iterator();
                while (iter.hasNext()) {
                    Element eg = (Element) iter.next();
                    if (DomTools.getAttributeBoolean(eg, "visible", false, false)) {
                        int gid = DomTools.getAttributeInt(eg, "id", 0, true);
                        if (gid > 0) {
                            Group grp = new Group(gid, DomTools.getChildText(eg, "Name", "G/" + gid, false),
                                    DomTools.getAttributeBoolean(eg, "selected", false, false));
                            groupList.add(grp);

                            // group color
                            String sc = DomTools.getChildText(eg, "Color", null, false);
                            if (sc != null) {
                                try {
                                    grp.color = Color.decode(sc);
                                } catch (NumberFormatException ex) {
                                    log.warn("Invalid color attribute on Group node, defaulting to grey");
                                }
                            }

                            // state color
                            grp.stateColor = Color.red;
                            String state = DomTools.getAttributeString(eg, "state", "stopped", false);
                            if (state.equals("started"))
                                grp.stateColor = Color.green;
                            else if (state.equals("paused"))
                                grp.stateColor = Color.orange;
                        }
                    }
                }
            }
        }
    }

    if (doc == null) {
        g.setColor(Color.black);
        String text = "No configuration loaded. Select 'Load configuration...' from the file menu.";
        g.drawString(text, (w - SwingUtilities.computeStringWidth(g.getFontMetrics(), text)) / 2, h * 5 / 12);
    } else {
        g.setFont(new Font("Dialog", Font.BOLD, 13));

        Iterator<Terminal> itert = terminalMap.values().iterator();
        while (itert.hasNext()) {
            Terminal t = itert.next();

            // Draw box
            int b = t.isSelected ? SERVERVIEW_SELECTION_BORDER : 1;
            g.setColor(Color.black);
            g.fillRect(t.x + SERVERVIEW_SELECTION_BORDER - b, t.y + SERVERVIEW_SELECTION_BORDER - b,
                    SERVERVIEW_TERMINAL_WIDTH + 2 * b, SERVERVIEW_TERMINAL_HEIGHT + 2 * b);
            g.setColor(t.groupColor == null ? Color.white : t.groupColor);
            g.fillRect(t.x + SERVERVIEW_SELECTION_BORDER, t.y + SERVERVIEW_SELECTION_BORDER,
                    SERVERVIEW_TERMINAL_WIDTH, SERVERVIEW_TERMINAL_HEIGHT);

            // Inner areas
            Rectangle r = new Rectangle(t.x + SERVERVIEW_SELECTION_BORDER + SERVERVIEW_TERMINAL_BORDER,
                    t.y + SERVERVIEW_SELECTION_BORDER + SERVERVIEW_TERMINAL_BORDER,
                    SERVERVIEW_TERMINAL_WIDTH - 2 * SERVERVIEW_TERMINAL_BORDER,
                    g.getFontMetrics().getHeight() + 4);

            g.setColor(Color.white);
            g.fillRect(r.x, r.y, r.width, r.height);
            g.fillRect(r.x, r.y + r.height + SERVERVIEW_TERMINAL_BORDER + 2, r.width,
                    SERVERVIEW_TERMINAL_HEIGHT - 3 * SERVERVIEW_TERMINAL_BORDER - r.height - 2);
            g.setColor(Color.black);
            g.drawRect(r.x, r.y, r.width, r.height);
            g.drawRect(r.x, r.y + r.height + SERVERVIEW_TERMINAL_BORDER + 2, r.width,
                    SERVERVIEW_TERMINAL_HEIGHT - 3 * SERVERVIEW_TERMINAL_BORDER - r.height - 2);

            // Name of terminal and group
            if (server.isaClient(t.tid)) {
                g.drawImage(indicatorIsa.getImage(), r.x + r.width - 20, r.y + SERVERVIEW_TERMINAL_HEIGHT - 26,
                        null);
            }
            g.drawString(t.name + " " + t.groupName, r.x + 4, r.y + r.height - 4);

            double px = r.x + 4;
            double py = r.y + r.height + SERVERVIEW_TERMINAL_BORDER + 5;

            // Draw monitored indicator
            if (t.isMonitored) {
                g.drawImage(indicatorMonitored.getImage(), r.x + r.width - 9, r.y + 3, null);
            }

            // Draw relocated indicator
            if (t.isRelocated) {
                g.drawImage(indicatorRelocated.getImage(), r.x + r.width - 9, r.y + 13, null);
            }

            // Draw online indicator
            r.setBounds(r.x, r.y + r.height, r.width, 3);
            g.setColor(t.isOnline ? Color.green : Color.red);
            g.fillRect(r.x, r.y, r.width, r.height);
            g.setColor(Color.black);
            g.drawRect(r.x, r.y, r.width, r.height);

            // Roles
            if (t.roles.length() > 0) {
                LineBreakMeasurer lbm = new LineBreakMeasurer(new AttributedString(t.roles).getIterator(),
                        new FontRenderContext(null, false, true));

                TextLayout layout;
                while ((layout = lbm
                        .nextLayout(SERVERVIEW_TERMINAL_WIDTH - 2 * SERVERVIEW_TERMINAL_BORDER)) != null) {
                    if (py < t.y + SERVERVIEW_TERMINAL_HEIGHT) {
                        py += layout.getAscent();
                        layout.draw((Graphics2D) g, (int) px, (int) py);
                        py += layout.getDescent() + layout.getLeading();
                    }
                }
            }
        }

        // Draw group indicators
        int nbrGroupsInRow = w
                / (2 * Constants.SERVERVIEW_SELECTION_BORDER + 2 + Constants.SERVERVIEW_GROUP_WIDTH);
        if (nbrGroupsInRow < 1)
            nbrGroupsInRow = 1;
        int nbrGroupRows = (groupList.size() + nbrGroupsInRow - 1) / nbrGroupsInRow;

        int innerWidth = Constants.SERVERVIEW_GROUP_WIDTH;
        int innerHeight = g.getFontMetrics().getHeight() + 5;

        int outerWidth = innerWidth + 2 * Constants.SERVERVIEW_SELECTION_BORDER + 2;
        int outerHeight = innerHeight + 2 * Constants.SERVERVIEW_SELECTION_BORDER + 2;

        int x = 0;
        int y = h - outerHeight * nbrGroupRows;

        g.setColor(Color.white);
        g.fillRect(0, y, w, h - y);
        g.setColor(Color.black);
        g.drawLine(0, y - 1, w - 1, y - 1);

        Iterator<Group> iterg = groupList.iterator();
        while (iterg.hasNext()) {
            Group grp = iterg.next();

            // Group box
            grp.boundingRect.setBounds(x, y, outerWidth, outerHeight);
            int b = grp.isSelected ? Constants.SERVERVIEW_SELECTION_BORDER : 1;
            g.setColor(Color.black);
            g.fillRect(x + Constants.SERVERVIEW_SELECTION_BORDER - b + 1,
                    y + Constants.SERVERVIEW_SELECTION_BORDER - b + 1, innerWidth + 2 * b, innerHeight + 2 * b);
            g.setColor(grp.color);
            g.fillRect(x + Constants.SERVERVIEW_SELECTION_BORDER + 1,
                    y + Constants.SERVERVIEW_SELECTION_BORDER + 1, innerWidth, innerHeight);

            g.setColor(Color.black);
            g.drawString(grp.name, x + Constants.SERVERVIEW_SELECTION_BORDER + 4,
                    y + Constants.SERVERVIEW_SELECTION_BORDER + innerHeight - 4 + 1);

            // Draw started indicator
            g.setColor(grp.stateColor);
            g.fillRect(x + Constants.SERVERVIEW_SELECTION_BORDER + 1,
                    y + Constants.SERVERVIEW_SELECTION_BORDER + 1, innerWidth, 2);
            g.setColor(Color.black);
            g.drawLine(x + Constants.SERVERVIEW_SELECTION_BORDER + 1,
                    y + Constants.SERVERVIEW_SELECTION_BORDER + 3,
                    x + Constants.SERVERVIEW_SELECTION_BORDER + 1 + innerWidth,
                    y + Constants.SERVERVIEW_SELECTION_BORDER + 3);

            x += outerWidth;
            if ((x + outerWidth) > w) {
                x = 0;
                y += outerHeight;
            }
        }
    }

    // Store cached version
    documentVersion = updateDocumentVersion;

    g.setColor(storedCol);
    g.setFont(storedFont);
}

From source file:com.github.lucapino.sheetmaker.renderer.JavaTemplateRenderer.java

public void drawString(Graphics g, String text, RectangularShape bounds, Align align, double angle,
        boolean multiline) {
    Graphics2D g2 = (Graphics2D) g;
    Font font = g2.getFont();/* www.j  a  v  a2s .c o m*/
    if (angle != 0) {
        g2.setFont(font.deriveFont(AffineTransform.getRotateInstance(Math.toRadians(angle))));
    }

    Rectangle2D sSize = g2.getFontMetrics().getStringBounds(text, g2);
    Point2D pos = getPoint(bounds, align);
    double x = pos.getX();
    double y = pos.getY() + sSize.getHeight();

    switch (align) {
    case TopCenter:
    case BottomCenter:
    case Center:
        x -= (sSize.getWidth() / 2);
        break;
    case TopRight:
    case MiddleRight:
    case BottomRight:
        x -= (sSize.getWidth());
        break;
    case BottomLeft:
    case MiddleLeft:
    case TopLeft:
        break;
    }
    if (multiline) {
        // Create a new LineBreakMeasurer from the paragraph.
        // It will be cached and re-used.
        //if (lineMeasurer == null) {
        AttributedCharacterIterator paragraph = new AttributedString(text).getIterator();
        paragraphStart = paragraph.getBeginIndex();
        paragraphEnd = paragraph.getEndIndex();
        FontRenderContext frc = g2.getFontRenderContext();
        lineMeasurer = new LineBreakMeasurer(paragraph, frc);
        //}

        // Set break width to width of Component.
        float breakWidth = (float) bounds.getWidth();
        float drawPosY = (float) y;
        // Set position to the index of the first character in the paragraph.
        lineMeasurer.setPosition(paragraphStart);

        // Get lines until the entire paragraph has been displayed.
        while (lineMeasurer.getPosition() < paragraphEnd) {

            // Retrieve next layout. A cleverer program would also cache
            // these layouts until the component is re-sized.
            TextLayout layout = lineMeasurer.nextLayout(breakWidth);

            // Compute pen x position. If the paragraph is right-to-left we
            // will align the TextLayouts to the right edge of the panel.
            // Note: this won't occur for the English text in this sample.
            // Note: drawPosX is always where the LEFT of the text is placed.
            float drawPosX = layout.isLeftToRight() ? (float) x : (float) x + breakWidth - layout.getAdvance();

            // Move y-coordinate by the ascent of the layout.
            drawPosY += layout.getAscent();

            // Draw the TextLayout at (drawPosX, drawPosY).
            layout.draw(g2, drawPosX, drawPosY);

            // Move y-coordinate in preparation for next layout.
            drawPosY += layout.getDescent() + layout.getLeading();
        }
    } else {
        g2.drawString(text, (float) x, (float) y);
    }
    g2.setFont(font);
}

From source file:ru.runa.wfe.graph.image.figure.AbstractFigure.java

private int drawText(Graphics2D graphics, String text, int hOffset) {
    Rectangle r = getTextBoundsRectangle();
    Rectangle2D textBounds = graphics.getFontMetrics().getStringBounds(text, graphics);
    if (textBounds.getWidth() > r.getWidth() - 4) {
        int y = coords[1] + hOffset;
        AttributedString attributedString = new AttributedString(text);
        attributedString.addAttribute(TextAttribute.FONT, graphics.getFont());
        AttributedCharacterIterator characterIterator = attributedString.getIterator();
        LineBreakMeasurer measurer = new LineBreakMeasurer(characterIterator, graphics.getFontRenderContext());
        while (measurer.getPosition() < characterIterator.getEndIndex()) {
            TextLayout textLayout = measurer.nextLayout((float) r.getWidth() - 4);
            y += textLayout.getAscent();
            float x = (float) (r.getCenterX() + 2 - textLayout.getBounds().getCenterX());
            textLayout.draw(graphics, x, y);
            y += textLayout.getDescent() + textLayout.getLeading();
        }//from www . j  ava  2s. c o  m
        return y - coords[1];
    } else {
        graphics.drawString(text, (float) (r.getCenterX() + 2 - textBounds.getCenterX()),
                (float) (coords[1] + textBounds.getHeight() + hOffset));
        return (int) (textBounds.getHeight() + hOffset + 3);
    }
}