Drawing a Paragraph of Text : TextLayout « 2D Graphics « Java Tutorial






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

import javax.swing.JFrame;
import javax.swing.JPanel;

public class BasicShapes extends JPanel {

  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    drawParagraph(g2d, "adfasdfaf", 20);
  }

  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();
      tl.draw(g, 0, y);
      y += tl.getDescent() + tl.getLeading();
    }
  }

  public static void main(String[] args) {

    JFrame frame = new JFrame("Basic Shapes");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new BasicShapes());
    frame.setSize(350, 250);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}








16.21.TextLayout
16.21.1.Styled TextStyled Text
16.21.2.Text Layout with mouse clicking and selecting actionText Layout with mouse clicking and selecting action
16.21.3.Draw text with TextLayout
16.21.4.Make your own animation from a series of images
16.21.5.Drawing a Paragraph of Text
16.21.6.Getting the Shape from the Outline of Text
16.21.7.Drawing Text with Mixed Styles
16.21.8.Line Break Measurer DemoLine Break Measurer Demo