Example usage for java.awt.font TextAttribute FONT

List of usage examples for java.awt.font TextAttribute FONT

Introduction

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

Prototype

TextAttribute FONT

To view the source code for java.awt.font TextAttribute FONT.

Click Source Link

Document

Attribute key used to provide the font to use to render text.

Usage

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 w  w w  .j  a v  a 2s  . c  o 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. ja va2s  .c o 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  ww w . jav  a 2s  . 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:TextLayoutWithCarets.java

private void initialize(Graphics2D g2) {
    String s = "Java Source and Support.";
    // Create a plain and italic font.
    int fontSize = 32;
    Font font = new Font("Lucida Sans Regular", Font.PLAIN, fontSize);
    Font italicFont = new Font("Lucida Sans Oblique", Font.ITALIC, fontSize);
    // Create an Attributed String
    AttributedString as = new AttributedString(s);
    as.addAttribute(TextAttribute.FONT, font);
    as.addAttribute(TextAttribute.FONT, italicFont, 2, 5);
    // Get the iterator.
    AttributedCharacterIterator iterator = as.getIterator();
    // Create a TextLayout.
    FontRenderContext frc = g2.getFontRenderContext();
    mLayout = new TextLayout(iterator, frc);

    mHit = mLayout.getNextLeftHit(1);/*from  w w  w  .j a  v a2s.c  o  m*/

    // Respond to left and right arrow keys.

    mInitialized = true;
}

From source file:AttributesApp.java

public AttributesApp() {
    setBackground(Color.lightGray);
    setSize(500, 200);//  w w w.j a  v  a 2 s.c  o m

    attribString = new AttributedString(text);

    GeneralPath star = new GeneralPath();
    star.moveTo(0, 0);
    star.lineTo(10, 30);
    star.lineTo(-10, 10);
    star.lineTo(10, 10);
    star.lineTo(-10, 30);
    star.closePath();
    GraphicAttribute starShapeAttr = new ShapeGraphicAttribute(star, GraphicAttribute.TOP_ALIGNMENT, false);
    attribString.addAttribute(TextAttribute.CHAR_REPLACEMENT, starShapeAttr, 0, 1);
    attribString.addAttribute(TextAttribute.FOREGROUND, new Color(255, 255, 0), 0, 1);

    int index = text.indexOf("Java Source");
    attribString.addAttribute(TextAttribute.FOREGROUND, Color.blue, index, index + 7);
    Font font = new Font("sanserif", Font.ITALIC, 40);
    attribString.addAttribute(TextAttribute.FONT, font, index, index + 7);

    loadImage();
    BufferedImage bimage = new BufferedImage(image.getWidth(this), image.getHeight(this),
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D big = bimage.createGraphics();
    big.drawImage(image, null, this);
    GraphicAttribute javaImageAttr = new ImageGraphicAttribute(bimage, GraphicAttribute.TOP_ALIGNMENT, 0, 0);

    index = text.indexOf("Java");
    attribString.addAttribute(TextAttribute.CHAR_REPLACEMENT, javaImageAttr, index - 1, index);

    font = new Font("serif", Font.BOLD, 60);
    attribString.addAttribute(TextAttribute.FONT, font, index, index + 4);
    attribString.addAttribute(TextAttribute.FOREGROUND, new Color(243, 63, 163), index, index + 4); // Start and end indexes.

    index = text.indexOf("source");
    attribString.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON, index, index + 2);

    index = text.indexOf("and support");
    font = new Font("sanserif", Font.ITALIC, 40);
    attribString.addAttribute(TextAttribute.FONT, font, index, index + 10);

    attribString.addAttribute(TextAttribute.FOREGROUND, Color.white, index, index + 2); // Start and end indexes.
    attribString.addAttribute(TextAttribute.FOREGROUND, Color.blue, index + 3, index + 10); // Start and end indexes.
}

From source file:forge.view.arcane.util.OutlinedLabel.java

/** {@inheritDoc} */
@Override//from   w w w  . j a v  a 2s  .c  o  m
public final void paint(final Graphics g) {
    if (getText().length() == 0) {
        return;
    }

    Dimension size = getSize();
    //
    //        if( size.width < 50 ) {
    //            g.setColor(Color.cyan);
    //            g.drawRect(0, 0, size.width-1, size.height-1);
    //        }

    Graphics2D g2d = (Graphics2D) g;

    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

    int textX = outlineSize, textY = 0;
    int wrapWidth = Math.max(0, wrap ? size.width - outlineSize * 2 : Integer.MAX_VALUE);

    final String text = getText();
    AttributedString attributedString = new AttributedString(text);
    if (!StringUtils.isEmpty(text)) {
        attributedString.addAttribute(TextAttribute.FONT, getFont());
    }
    AttributedCharacterIterator charIterator = attributedString.getIterator();
    FontRenderContext fontContext = g2d.getFontRenderContext();

    LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator,
            BreakIterator.getWordInstance(Locale.ENGLISH), fontContext);
    int lineCount = 0;
    while (measurer.getPosition() < charIterator.getEndIndex()) {
        measurer.nextLayout(wrapWidth);
        lineCount++;
        if (lineCount > 2) {
            break;
        }
    }
    charIterator.first();
    // Use char wrap if word wrap would cause more than two lines of text.
    if (lineCount > 2) {
        measurer = new LineBreakMeasurer(charIterator, BreakIterator.getCharacterInstance(Locale.ENGLISH),
                fontContext);
    } else {
        measurer.setPosition(0);
    }
    while (measurer.getPosition() < charIterator.getEndIndex()) {
        TextLayout textLayout = measurer.nextLayout(wrapWidth);
        float ascent = textLayout.getAscent();
        textY += ascent; // Move down to baseline.

        g2d.setColor(outlineColor);
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.8f));

        textLayout.draw(g2d, textX + outlineSize, textY - outlineSize);
        textLayout.draw(g2d, textX + outlineSize, textY + outlineSize);
        textLayout.draw(g2d, textX - outlineSize, textY - outlineSize);
        textLayout.draw(g2d, textX - outlineSize, textY + outlineSize);

        g2d.setColor(getForeground());
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
        textLayout.draw(g2d, textX, textY);

        // Move down to top of next line.
        textY += textLayout.getDescent() + textLayout.getLeading();
    }
}

From source file:net.sf.jasperreports.engine.util.JRFontUtil.java

/**
 * Fills the supplied Map parameter with attributes copied from the JRFont parameter.
 * The attributes include the TextAttribute.FONT, which has a java.awt.Font object as value.
 * @deprecated Replaced by {@link #getAttributesWithoutAwtFont(Map, JRFont)}.
 *//*from w  w w.  ja  v  a  2s  .c o m*/
public static Map<Attribute, Object> getAttributes(Map<Attribute, Object> attributes, JRFont font,
        Locale locale) {
    //Font awtFont = getAwtFont(font);//FIXMEFONT optimize so that we don't load the AWT font for all exporters.
    Font awtFont = getAwtFontFromBundles(font.getFontName(),
            ((font.isBold() ? Font.BOLD : Font.PLAIN) | (font.isItalic() ? Font.ITALIC : Font.PLAIN)),
            font.getFontSize(), locale, true);
    if (awtFont != null) {
        attributes.put(TextAttribute.FONT, awtFont);
    }

    getAttributesWithoutAwtFont(attributes, font);

    return attributes;
}

From source file:TextFormat.java

/**
 * Lazy evaluation of the List of TextLayout objects corresponding to this
 * MText. Some things are approximations!
 *//*  w w w  . j  a  v  a 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

/**
 * Initialize the various maps, fonts, etc..
 */// w ww . j  a v a  2 s  .  c om
@PostConstruct
protected void postActivate() {
    try {
        // Init the coverMap and load the images
        coverMap = new HashMap<String, byte[]>();
        List<BookCover> covers = coverDisplayData.getCovers();
        for (BookCover cover : covers) {
            coverMap.put(cover.getCoverName(),
                    readResourceToByteArray("/" + cover.getImgUrl(), servletContext));
        }

        // Load needed fonts
        medulaOneRegularFont = Font.createFont(Font.TRUETYPE_FONT,
                servletContext.getResourceAsStream("/Olhie/font/MedulaOne-Regular.ttf"));
        medulaOneRegularFont48 = medulaOneRegularFont.deriveFont(new Float(48.0));
        arialBoldFont13 = new Font("Arial Bold", Font.BOLD, 13);
        arialBoldFont16 = new Font("Arial Bold", Font.ITALIC, 16);

        // Init font maps
        // author
        authorFontMap = new Hashtable<TextAttribute, Object>();
        authorFontMap.put(TextAttribute.FONT, arialBoldFont16);
        authorFontMap.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD);

        // Title
        titleFontMap = new Hashtable<TextAttribute, Object>();
        titleFontMap.put(TextAttribute.FONT, medulaOneRegularFont48);
        titleFontMap.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD);

        // Back cover title
        backTitleFontMap = new Hashtable<TextAttribute, Object>();
        backTitleFontMap.put(TextAttribute.FONT, arialBoldFont13);
        backTitleFontMap.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD);
        backTitleFontMap.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_LOW_ONE_PIXEL);

        // Build palette factory
        palFac = new PaletteFactory();

    } catch (Exception e) {
        log.log(Level.SEVERE, "Error occured during BookCoverImageService initialization.", e);
    }
}

From source file:net.sf.jasperreports.engine.fill.SimpleTextLineWrapper.java

protected int measureExactLineBreakIndex(float width, int endLimit, boolean requireWord) {
    //FIXME would it be faster to create and cache a LineBreakMeasurer for the whole paragraph?
    Map<Attribute, Object> attributes = new HashMap<Attribute, Object>();
    // we only need the font as it includes the size and style
    attributes.put(TextAttribute.FONT, fontInfo.fontInfo.font);

    String textLine = paragraphText.substring(paragraphPosition, endLimit);
    AttributedString attributedLine = new AttributedString(textLine, attributes);

    // we need a fresh iterator for the line
    BreakIterator breakIterator = paragraphTruncateAtChar ? BreakIterator.getCharacterInstance()
            : BreakIterator.getLineInstance();
    LineBreakMeasurer breakMeasurer = new LineBreakMeasurer(attributedLine.getIterator(), breakIterator,
            context.getFontRenderContext());
    int breakIndex = breakMeasurer.nextOffset(width, endLimit - paragraphPosition, requireWord)
            + paragraphPosition;//from ww w .  ja  v  a  2s . c  o m
    if (logTrace) {
        log.trace("exact line break index measured at " + (paragraphOffset + breakIndex));
    }

    return breakIndex;
}