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

intgetStringWidth(FontMetrics f, String s)
get String Width
int width = 0;
for (int i = 0; i < s.length(); i++) {
    if (s.charAt(i) < 256)
        width += f.getWidths()[s.charAt(i)];
    else
        width += f.getWidths()['a'];
return width;
...
intgetStringWidth(Graphics g, Font font, String x)
Returns the width a string would have if painted with a specific font.
return g.getFontMetrics(font).stringWidth(x);
intgetStringWidth(Graphics2D g2, final String str)
get String Width
Rectangle2D bounds = g2.getFont().getStringBounds(str, g2.getFontRenderContext());
return (int) bounds.getWidth();
intgetStringWidth(Graphics2D g2d, String info, Font font)
get String Width
FontMetrics fm = g2d.getFontMetrics(font);
Rectangle2D rect = fm.getStringBounds(info, g2d);
return (int) (rect.getWidth());
intgetStringWidth(String loginID, Font font)
get String Width
AffineTransform affinetransform = new AffineTransform();
FontRenderContext frc = new FontRenderContext(affinetransform, true, true);
return (int) ((font.getStringBounds(loginID, frc)).getWidth());
intgetStringWidth(String s, FontMetrics fm)
Compute just the width of the given string with the given FontMetrics.
return fm.stringWidth(s);
floatgetStringWidth(String str, java.awt.Font font)
Get the string width for a particular string given the font.
Rectangle2D rect = font.getStringBounds(str, 0, str.length(),
        new FontRenderContext(new AffineTransform(), true, true));
return (float) rect.getWidth();
StringgetTextForWidth(double bboxWth, String txt, Font font)
get Text For Width
java.awt.FontMetrics fm = Toolkit.getDefaultToolkit().getFontMetrics(font);
int width = fm.stringWidth(txt);
String origText = txt;
while (true) {
    if (width < bboxWth)
        break;
    txt = txt.substring(0, txt.length() - 1);
    width = fm.stringWidth(txt);
...
intgetTextWidth(String text, Graphics g, String newLineSplit)
get Text Width
int width = 0;
String[] lines = text.split(newLineSplit);
for (String line : lines) {
    int w = g.getFontMetrics().stringWidth(line);
    if (w > width) {
        width = w;
return width;
intgetWidth(String s, Graphics g)
Get the length of a string in pixels for a given graphics context
return g.getFontMetrics().stringWidth(s);