import java.awt.*; import java.awt.geom.*; public class StringUtilities { public static int getWidthOf(String str, Graphics g) { return getSizeOf(str, g).width; } public static int getHeightOf(String str, Graphics g) { return getSizeOf(str, g).height; } public static Dimension getSizeOf(String str, Graphics g) { FontMetrics fm = g.getFontMetrics(); Rectangle2D rect = fm.getStringBounds(str, g); return new Dimension((int)rect.getWidth(), (int)rect.getHeight()); } public static void drawInRect(String str, Rectangle rc, Graphics g) { Font f = g.getFont(); FontMetrics fm=g.getFontMetrics(); int lineSep=3; int spaceSep = getWidthOf("w"); int height = fm.getHeight(); int x = 0; int y = height + lineSep; String[] split = str.split(" "); for(String s:split) { int strWidth = getWidthOf(s,g); if(x + spaceSep + strWidth > rc.width - spaceSep) { x = 0; y += height + lineSep; } g.drawString(s, x + rc.x, y +rc.y); x += strWidth + spaceSep; } } }