Returns the string width for a given Font and string. - Java 2D Graphics

Java examples for 2D Graphics:Font

Description

Returns the string width for a given Font and string.

Demo Code

/*//from  w w w.  j  a v a2 s .  c o  m
 * OpenBench LogicSniffer / SUMP project 
 *
 * 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.,
 * 51 Franklin St, Fifth Floor, Boston, MA 02110, USA
 *
 * Copyright (C) 2006-2010 Michael Poppitz, www.sump.org
 * Copyright (C) 2010 J.W. Janssen, www.lxtreme.nl
 */
//package com.java2s;
import java.awt.*;

import java.awt.image.*;
import javax.swing.*;

public class Main {
    /** The key for the default label font as used by Swing. */
    public static final String SWING_LABEL_FONT = "Label.font";

    /**
     * Returns the string width for a given {@link Font} and string.
     * 
     * @param aFont
     *          the font to create the string width;
     * @param aString
     *          the string to get the width for.
     * @return a string width, >= 0.
     */
    public static int getStringWidth(final Font aFont, final String aString) {
        final FontMetrics frc = createFontMetrics(aFont);
        return SwingUtilities.computeStringWidth(frc, aString);
    }

    /**
     * Returns the string width for the default label font and string.
     * 
     * @param aString
     *          the string to get the width for.
     * @return a string width, >= 0.
     */
    public static int getStringWidth(final String aString) {
        return getStringWidth(UIManager.getFont(SWING_LABEL_FONT), aString);
    }

    /**
     * Creates (in a rather clumsy way) the font metrics for a given {@link Font}.
     * 
     * @param aFont
     *          the font instance to create the font metrics for, cannot be
     *          <code>null</code>.
     * @return a font metrics, never <code>null</code>.
     */
    private static FontMetrics createFontMetrics(final Font aFont) {
        BufferedImage img = new BufferedImage(1, 1,
                BufferedImage.TYPE_INT_ARGB);
        Graphics canvas = img.getGraphics();

        try {
            return canvas.getFontMetrics(aFont);
        } finally {
            canvas.dispose();
            canvas = null;
            img = null;
        }
    }
}

Related Tutorials