Java Font Text Width getTextForWidth(double bboxWth, String txt, Font font)

Here you can find the source of getTextForWidth(double bboxWth, String txt, Font font)

Description

get Text For Width

License

Apache License

Declaration

public static String getTextForWidth(double bboxWth, String txt, Font font) 

Method Source Code

//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();
    }
}

Related

  1. getStringWidth(Graphics2D g2, final String str)
  2. getStringWidth(Graphics2D g2d, String info, Font font)
  3. getStringWidth(String loginID, Font font)
  4. getStringWidth(String s, FontMetrics fm)
  5. getStringWidth(String str, java.awt.Font font)
  6. getTextWidth(String text, Graphics g, String newLineSplit)
  7. getWidth(String s, Graphics g)
  8. getWidthForText(String txt, Font font)
  9. getWidthOfDots(FontMetrics fontMetrics)