Here you can find the source of getStringWidth(Graphics2D g2, final String str)
public static int getStringWidth(Graphics2D g2, final String str)
//package com.java2s; //License from project: Open Source License import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; public class Main { public static int getStringWidth(Graphics2D g2, final String str) { Rectangle2D bounds = g2.getFont().getStringBounds(str, g2.getFontRenderContext()); return (int) bounds.getWidth(); }//from www . j a v a 2 s . c om }