Drawing a Paragraph of Text - Java 2D Graphics

Java examples for 2D Graphics:Text

Description

Drawing a Paragraph of Text

Demo Code

import java.awt.Graphics2D;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextLayout;
import java.text.AttributedString;

public class Main {
  public void drawParagraph(Graphics2D g, String paragraph, float width) {
    LineBreakMeasurer linebreaker = new LineBreakMeasurer(new AttributedString(
        paragraph).getIterator(), g.getFontRenderContext());

    float y = 0.0f;
    while (linebreaker.getPosition() < paragraph.length()) {
      TextLayout tl = linebreaker.nextLayout(width);

      y += tl.getAscent();//from  ww  w .  j  a v  a2 s . c  o m
      tl.draw(g, 0, y);
      y += tl.getDescent() + tl.getLeading();
    }
  }
}

Related Tutorials