Here you can find the source of getStringWidth(final String aString)
Parameter | Description |
---|---|
aString | the string to get the width for. |
public static int getStringWidth(final String aString)
//package com.java2s; /*//w w w . j a v a 2s .com * 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) 2010-2011 - J.W. Janssen, http://www.lxtreme.nl */ import java.awt.*; import java.awt.image.*; import javax.swing.*; public class Main { /** * 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("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; } } /** * Closes and disposes a given {@link Window}. * * @param aWindow * the window to close, if <code>null</code>, this method doesn't do * anything. */ public static void dispose(final Window aWindow) { if (aWindow == null) { return; } if (aWindow.isVisible()) { aWindow.setVisible(false); } aWindow.dispose(); } }