Here you can find the source of getTextForWidth(double bboxWth, String txt, Font font)
public static String getTextForWidth(double bboxWth, String txt, Font font)
//package com.java2s; //License from project: Apache License import java.awt.Font; import java.awt.Toolkit; import java.util.Vector; public class Main { public static String getTextForWidth(Vector<String> splitTxt, double bboxWth, Font font) { String selTxt = "", prevSelTxt = ""; StringBuffer txt4Wt = new StringBuffer(); for (int i = 0; i < splitTxt.size(); i++) { txt4Wt.append(splitTxt.elementAt(i)); selTxt = getTextForWidth(bboxWth, txt4Wt.toString(), font); if (selTxt.length() < txt4Wt.toString().length()) { selTxt = prevSelTxt;//from www .j av a2 s .co m break; } prevSelTxt = selTxt; } // System.out.println("Prev Sel Txt: " + prevSelTxt + " selTxt: " + // selTxt); return selTxt; } public static String getTextForWidth(double bboxWth, String txt, Font font) { java.awt.FontMetrics fm = Toolkit.getDefaultToolkit().getFontMetrics(font); int width = fm.stringWidth(txt); String origText = txt; while (true) { if (width < bboxWth) break; txt = txt.substring(0, txt.length() - 1); width = fm.stringWidth(txt); } return txt; } public static String toString(String[] arrStrs) { StringBuffer strBuf = new StringBuffer(); for (int i = 0; i < arrStrs.length; i++) { strBuf.append(arrStrs[i] + ", "); } return strBuf.toString(); } }