Here you can find the source of findStringLimit(String aString, Font aFont, int aWidth)
private static int findStringLimit(String aString, Font aFont, int aWidth)
//package com.java2s; //License from project: Open Source License import java.awt.Font; import java.awt.font.FontRenderContext; import java.awt.geom.AffineTransform; public class Main { protected final static FontRenderContext mFontRenderContext = new FontRenderContext(new AffineTransform(), false, false);//from w ww. j ava 2 s. c o m private static int findStringLimit(String aString, Font aFont, int aWidth) { int min = 0; int max = aString.length(); while (Math.abs(min - max) > 1) { int mid = (max + min) / 2; int w = getStringLength(aString.substring(0, mid), aFont); //System.out.printf("%d\t%d\t%d\t%d\t%d\n", min, max, mid, aWidth, w); if (w > aWidth) { max = mid; } else { min = mid; } } return min; } public static int getStringLength(String aString, Font aFont) { return (int) aFont.getStringBounds(aString, mFontRenderContext).getWidth(); } }