Java Swing Font Width getStringWidth(Font font, String str)

Here you can find the source of getStringWidth(Font font, String str)

Description

Gets the width of the specified String.

License

Open Source License

Parameter

Parameter Description
str The String to get the width for.
font The font being the base of the measure.

Return

the width of the specified String.

Declaration

public static int getStringWidth(Font font, String str) 

Method Source Code

//package com.java2s;
/*/*from www  .j a v  a  2 s  .c o  m*/
 * TV-Browser
 * Copyright (C) 04-2003 Martin Oberhauser (martin_oat@yahoo.de)
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * CVS information:
 *  $RCSfile$
 *   $Source$
 *     $Date: 2010-11-14 17:44:44 +0100 (Sun, 14 Nov 2010) $
 *   $Author: bananeweizen $
 * $Revision: 6823 $
 */

import java.awt.Font;
import java.awt.FontMetrics;

import javax.swing.JLabel;

public class Main {
    /** The helper label. */
    private static final JLabel HELPER_LABEL = new JLabel();

    /**
     * Gets the width of the specified String.
     *
     * @param str
     *          The String to get the width for.
     * @param font
     *          The font being the base of the measure.
     * @return the width of the specified String.
     */
    public static int getStringWidth(Font font, String str) {
        if (str == null) {
            return 0;
        }

        FontMetrics metrics = HELPER_LABEL.getFontMetrics(font);
        return metrics.stringWidth(str);
    }
}

Related

  1. estimateWidth(Font font, String msg)
  2. getEditor(String html, int width, Color transparentColor, Font font)
  3. getHTMLTextForWidth(JComponent comp, double bboxWth, String txt, Font font)
  4. getStringWidth(final Font aFont, final String aString)
  5. getTextWidth(final String text, final Font font)
  6. getTextWidth(Font font, String text)
  7. isFixedWidthFont(String fontName, Component component)