Here you can find the source of shortenString(FontMetrics fm, String str, int maxWidth)
Parameter | Description |
---|---|
fm | The font the text will be rendered in. |
str | The string to trimmed. |
maxWidth | The maximum width that the string is allowed to be. |
public static String shortenString(FontMetrics fm, String str, int maxWidth)
//package com.java2s; /*//from www . ja va 2 s .co m * Copyright 2002-2003 (C) B. K. Oxley (binkley) <binkley@alumni.rice.edu> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ import java.awt.FontMetrics; public class Main { /** * Trim a string from the left to fit within the specified width. * * @param fm The font the text will be rendered in. * @param str The string to trimmed. * @param maxWidth The maximum width that the string is allowed to be. * @return String The trimmed string. */ public static String shortenString(FontMetrics fm, String str, int maxWidth) { for (int i = str.length(); i > 0; i -= 5) { String shortedString = "..." + str.substring(str.length() - i); int width = fm.stringWidth(shortedString); //System.out.println("testing '"+foo+"' = "+width); if (width < maxWidth) { return shortedString; } } return ""; } }