Java Utililty Methods Font Text Width

List of utility methods to do Font Text Width

Description

The list of methods to do Font Text Width are organized into topic(s).

Method

intgetWidthForText(String txt, Font font)
get Width For Text
java.awt.FontMetrics fm = Toolkit.getDefaultToolkit().getFontMetrics(font);
int width = fm.stringWidth(txt);
return width;
intgetWidthOfDots(FontMetrics fontMetrics)
get Width Of Dots
return fontMetrics.stringWidth("...");
voidsetFixedWidthFont(Component comp)
Set the font on the component to be monospaced
Font lblFont = comp.getFont();
Font monoFont = new Font("Monospaced", lblFont.getStyle(), lblFont.getSize());
comp.setFont(monoFont);
FontshrinkFontForWidth(Font base, String text, int desiredWidth, Graphics getMetrics)
Finds the smallest font size that will fit a string within a given width.
FontMetrics metrics = getMetrics.getFontMetrics(base);
while (metrics.stringWidth(text) > desiredWidth) {
    base = base.deriveFont((float) base.getSize() - 1);
return base;
intstringPixelWidth(String text, FontMetrics fm)
string Pixel Width
return fm.charsWidth(text.toCharArray(), 0, text.length());
intstringWidth(final FontMetrics fm, final String string)
Returns the width of the passed in String.
if (string == null || string.equals("")) {
    return 0;
return fm.stringWidth(string);
intstringWidth(Graphics g, String s)
Returns the width of string in the current Graphics
FontMetrics fm = g.getFontMetrics(g.getFont());
if (fm == null)
    return -1;
return fm.stringWidth(s);
intstringWidth(Graphics2D g, String s)
string Width
return g.getFontMetrics().stringWidth(s);
intstringWidth(java.awt.Font font, String string)
Return a string width for a given font.
return (int) (0.6 * font.getSize() * string.length());
intstringWidth(String text, Font font)
string Width
setupAntialiasing(ourGraphics, true, true);
return ourGraphics.getFontMetrics(font).stringWidth(text);