Here you can find the source of drawWrappedText(Graphics2D g2, float x, float y, float width, String text)
public static float drawWrappedText(Graphics2D g2, float x, float y, float width, String text)
//package com.java2s; //License from project: Open Source License import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.font.FontRenderContext; import java.awt.font.LineBreakMeasurer; import java.awt.font.TextAttribute; import java.awt.font.TextLayout; import java.awt.geom.AffineTransform; import java.text.AttributedCharacterIterator; import java.text.AttributedString; public class Main { /** Draw given text to given Graphics2D view starting at x,y and wrapping * lines at width pixels. If the y coordinate is negative, take it as * maximum y position. Return new y. */// ww w. jav a 2 s . c o m public static float drawWrappedText(Graphics2D g2, float x, float y, float width, String text) { if (text == null || text.length() == 0) return y; FontRenderContext frc = g2.getFontRenderContext(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, // Anti-alias! RenderingHints.VALUE_ANTIALIAS_ON); g2.setStroke(new BasicStroke(2.0f)); // 2-pixel lines AttributedString astr = new AttributedString(text); astr.addAttribute(TextAttribute.FONT, g2.getFont(), 0, text.length()); if (y < 0) { // Calculate real Y by laying out the text without output y = -y; AttributedCharacterIterator chars = astr.getIterator(); LineBreakMeasurer measurer = new LineBreakMeasurer(chars, frc); while (measurer.getPosition() < chars.getEndIndex()) { TextLayout layout = measurer.nextLayout(width); y -= layout.getAscent(); float dx = layout.isLeftToRight() ? 0 : (width - layout.getAdvance()); float sw = (float) layout.getBounds().getWidth(); float sh = (float) layout.getBounds().getHeight(); y -= layout.getDescent() + layout.getLeading(); } } AttributedCharacterIterator chars = astr.getIterator(); LineBreakMeasurer measurer = new LineBreakMeasurer(chars, frc); while (measurer.getPosition() < chars.getEndIndex()) { TextLayout layout = measurer.nextLayout(width); y += layout.getAscent(); float dx = layout.isLeftToRight() ? 0 : (width - layout.getAdvance()); float sw = (float) layout.getBounds().getWidth(); float sh = (float) layout.getBounds().getHeight(); Shape sha = layout.getOutline(AffineTransform.getTranslateInstance(x, y)); Color oldColor = g2.getColor(); g2.setColor(g2.getBackground()); g2.draw(sha); g2.setColor(oldColor); g2.fill(sha); y += layout.getDescent() + layout.getLeading(); } return y; } }