Java Font Text Width getStringWidth(Graphics g, Font font, String x)

Here you can find the source of getStringWidth(Graphics g, Font font, String x)

Description

Returns the width a string would have if painted with a specific font.

License

Open Source License

Parameter

Parameter Description
g - Graphics object to use
font - Font of interest
x - String to get the width

Return

Width the painted string would have with the font.

Declaration

public static int getStringWidth(Graphics g, Font font, String x) 

Method Source Code


//package com.java2s;
/*//w  w  w .ja v a2 s. com
 *  common-package - various java utilities
 *  Copyright (C) 2012  Johannes Steltzer
 *
 *  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 3 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, see <http://www.gnu.org/licenses/>.
 */

import java.awt.Font;
import java.awt.Graphics;

public class Main {
    /**
     * Returns the width a string would have if painted
     * with the current font. String will not be painted!
     * @param g - Graphics object to use with the desired font set
     * @param x - String to get the width
     * @return Width the painted string would have.
     */
    public static int getStringWidth(Graphics g, String x) {
        return g.getFontMetrics().stringWidth(x);
    }

    /**
      * Returns the width a string would have if painted
      * with a specific font. String will not be painted!
      * @param g - Graphics object to use
      * @param font - Font of interest
      * @param x - String to get the width
      * @return Width the painted string would have with the font.
      */
    public static int getStringWidth(Graphics g, Font font, String x) {
        return g.getFontMetrics(font).stringWidth(x);
    }
}

Related

  1. findWidth(FontMetrics metrics, char[] chars, int off, int len, float maxWidth, float[] outWidth)
  2. fontWidth(final Graphics graphics, final Font font, final String str)
  3. getStringWidth(final Font f, final String s)
  4. getStringWidth(Font font, String text)
  5. getStringWidth(FontMetrics f, String s)
  6. getStringWidth(Graphics2D g2, final String str)
  7. getStringWidth(Graphics2D g2d, String info, Font font)
  8. getStringWidth(String loginID, Font font)
  9. getStringWidth(String s, FontMetrics fm)