Here you can find the source of drawTextInBoundedArea(Graphics2D g2d, int x1, int y1, int x2, int y2, String text)
private static void drawTextInBoundedArea(Graphics2D g2d, int x1, int y1, int x2, int y2, String text)
//package com.java2s; //License from project: Apache License import java.awt.Graphics2D; import java.awt.font.FontRenderContext; import java.awt.font.LineBreakMeasurer; import java.awt.font.TextAttribute; import java.awt.font.TextLayout; import java.text.AttributedCharacterIterator; import java.text.AttributedString; public class Main { private static void drawTextInBoundedArea(Graphics2D g2d, int x1, int y1, int x2, int y2, String text) { float interline = 1; float width = x2 - x1; AttributedString as = new AttributedString(text); as.addAttribute(TextAttribute.FOREGROUND, g2d.getPaint()); as.addAttribute(TextAttribute.FONT, g2d.getFont()); AttributedCharacterIterator aci = as.getIterator(); FontRenderContext frc = new FontRenderContext(null, true, false); LineBreakMeasurer lbm = new LineBreakMeasurer(aci, frc); while (lbm.getPosition() < text.length()) { TextLayout tl = lbm.nextLayout(width); y1 += tl.getAscent();//from w ww. j a va 2s . co m tl.draw(g2d, x1, y1); y1 += tl.getDescent() + tl.getLeading() + (interline - 1.0f) * tl.getAscent(); if (y1 > y2) { break; } } } }