Example usage for java.text AttributedString getIterator

List of usage examples for java.text AttributedString getIterator

Introduction

In this page you can find the example usage for java.text AttributedString getIterator.

Prototype

public AttributedCharacterIterator getIterator() 

Source Link

Document

Creates an AttributedCharacterIterator instance that provides access to the entire contents of this string.

Usage

From source file:com.pureinfo.srm.common.ImageHelper.java

private static void draw(String _str, Graphics2D _g2, int _nX0, int _nY0, int _nX1, int _nY1) {
    Font font = new Font(getFontName(), Font.BOLD, getFontSize());
    AttributedString str = new AttributedString(_str);
    str.addAttribute(TextAttribute.FONT, font);
    str.addAttribute(TextAttribute.FOREGROUND, getColor());
    _g2.drawString(str.getIterator(), getNumber(_nX0, _nX1), (_nY0 + _nY1) * 2 / 3);
}

From source file:Main.java

public static int paintMultilineText(Graphics2D g2d, String text, int textX, int textWidth, int textY,
        int maxTextLineCount) {
    FontRenderContext frc = new FontRenderContext(new AffineTransform(), true, false);
    int fa = g2d.getFontMetrics().getAscent();

    if (text.length() == 0)
        return textY;

    int currOffset = 0;
    AttributedString attributedDescription = new AttributedString(text);
    attributedDescription.addAttribute(TextAttribute.FONT, g2d.getFont());
    LineBreakMeasurer lineBreakMeasurer = new LineBreakMeasurer(attributedDescription.getIterator(), frc);
    int lineCount = 0;
    while (true) {
        TextLayout tl = lineBreakMeasurer.nextLayout(textWidth);
        if (tl == null)
            break;

        int charCount = tl.getCharacterCount();
        String line = text.substring(currOffset, currOffset + charCount);

        g2d.drawString(line, textX, textY);

        textY += fa;//from  w  w w  . j a v  a  2  s.c  o  m
        currOffset += charCount;

        lineCount++;
        if ((maxTextLineCount > 0) && (lineCount == maxTextLineCount))
            break;
    }

    // textY += fh;

    return textY;
}

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.ja 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: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}
 *//*from  w w w . ja  v a 2  s.c  om*/
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:AttributedStringUtilities.java

/**
 * Tests two attributed strings for equality.
 * /*from ww  w.  java 2s.  c o  m*/
 * @param s1
 *          string 1 (<code>null</code> permitted).
 * @param s2
 *          string 2 (<code>null</code> permitted).
 * 
 * @return <code>true</code> if <code>s1</code> and <code>s2</code> are
 *         equal or both <code>null</code>, and <code>false</code>
 *         otherwise.
 */
public static boolean equal(AttributedString s1, AttributedString s2) {
    if (s1 == null) {
        return (s2 == null);
    }
    if (s2 == null) {
        return false;
    }
    AttributedCharacterIterator it1 = s1.getIterator();
    AttributedCharacterIterator it2 = s2.getIterator();
    char c1 = it1.first();
    char c2 = it2.first();
    int start = 0;
    while (c1 != CharacterIterator.DONE) {
        int limit1 = it1.getRunLimit();
        int limit2 = it2.getRunLimit();
        if (limit1 != limit2) {
            return false;
        }
        // if maps aren't equivalent, return false
        Map m1 = it1.getAttributes();
        Map m2 = it2.getAttributes();
        if (!m1.equals(m2)) {
            return false;
        }
        // now check characters in the run are the same
        for (int i = start; i < limit1; i++) {
            if (c1 != c2) {
                return false;
            }
            c1 = it1.next();
            c2 = it2.next();
        }
        start = limit1;
    }
    return c2 == CharacterIterator.DONE;
}

From source file:Main.java

/**
 * Serialises an <code>AttributedString</code> object.
 *
 * @param as  the attributed string object (<code>null</code> permitted).
 * @param stream  the output stream (<code>null</code> not permitted).
 *
 * @throws IOException if there is an I/O error.
 */// w  ww .jav a  2  s  . com
public static void writeAttributedString(AttributedString as, ObjectOutputStream stream) throws IOException {

    if (stream == null) {
        throw new IllegalArgumentException("Null 'stream' argument.");
    }
    if (as != null) {
        stream.writeBoolean(false);
        AttributedCharacterIterator aci = as.getIterator();
        // build a plain string from aci
        // then write the string
        StringBuffer plainStr = new StringBuffer();
        char current = aci.first();
        while (current != CharacterIterator.DONE) {
            plainStr = plainStr.append(current);
            current = aci.next();
        }
        stream.writeObject(plainStr.toString());

        // then write the attributes and limits for each run
        current = aci.first();
        int begin = aci.getBeginIndex();
        while (current != CharacterIterator.DONE) {
            // write the current character - when the reader sees that this
            // is not CharacterIterator.DONE, it will know to read the
            // run limits and attributes
            stream.writeChar(current);

            // now write the limit, adjusted as if beginIndex is zero
            int limit = aci.getRunLimit();
            stream.writeInt(limit - begin);

            // now write the attribute set
            Map atts = new HashMap(aci.getAttributes());
            stream.writeObject(atts);
            current = aci.setIndex(limit);
        }
        // write a character that signals to the reader that all runs
        // are done...
        stream.writeChar(CharacterIterator.DONE);
    } else {
        // write a flag that indicates a null
        stream.writeBoolean(true);
    }

}

From source file:TextAttributesSize.java

public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    AttributedString as1 = new AttributedString("1234567890");
    as1.addAttribute(TextAttribute.SIZE, 40);
    g2d.drawString(as1.getIterator(), 15, 60);
}

From source file:Main.java

public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    Font font = new Font("Serif", Font.PLAIN, 40);

    AttributedString as1 = new AttributedString("1234567890");
    as1.addAttribute(TextAttribute.FONT, font);
    g2d.drawString(as1.getIterator(), 15, 60);
}

From source file:MainClass.java

public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;

    String s = "\"www.java2s.com,\" www.java2s.com";

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    Font plainFont = new Font("Times New Roman", Font.PLAIN, 24);

    AttributedString as = new AttributedString(s);
    as.addAttribute(TextAttribute.FONT, plainFont);

    g2.drawString(as.getIterator(), 24, 70);

}

From source file:TextAttributesColor.java

public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    AttributedString as1 = new AttributedString("1234567890");
    as1.addAttribute(TextAttribute.FOREGROUND, Color.red, 0, 2);
    g2d.drawString(as1.getIterator(), 15, 60);
}