Java FontMetrics shortenString(FontMetrics fm, String str, int maxWidth)

Here you can find the source of shortenString(FontMetrics fm, String str, int maxWidth)

Description

Trim a string from the left to fit within the specified width.

License

Open Source License

Parameter

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.

Return

String The trimmed string.

Declaration

public static String shortenString(FontMetrics fm, String str,
        int maxWidth) 

Method Source Code

//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 "";
    }
}

Related

  1. maxStringPixelWidth(String[] strings, FontMetrics fm)
  2. paintString(String s, Graphics2D g2, Rectangle2D rect, float horizontal, float vertical)
  3. render(Graphics2D graphics, String str, Rectangle2D box, double xalign, double yalign)
  4. setComponentSize(Component component, int rows, int columns)
  5. setSizedFont(Graphics g, String text, float maxFontSize, int maxWidth)
  6. splitStringWithLength(String s, int length, FontMetrics fm)
  7. splitText(String text, String delim, FontMetrics fontMetrics, int width)
  8. stringByTruncatingToFitInWidth(String s, int width, Graphics g, String truncatedSuffix)
  9. stringDimension(Graphics g, Font f, String s)