Here you can find the source of getStringBounds(Graphics2D g2, String s)
public static Dimension getStringBounds(Graphics2D g2, String s)
//package com.java2s; //License from project: Open Source License import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.font.TextLayout; import java.awt.geom.Rectangle2D; public class Main { /**/* www. j a v a2s. c om*/ * Returns the @Rectangle2D surrounding a piece of text */ public static Dimension getStringBounds(Graphics2D g2, String s) { if (isStringEmpty(s)) return new Dimension(); TextLayout layout = new TextLayout(s, g2.getFont(), g2.getFontRenderContext()); Rectangle2D bounds = layout.getBounds(); return new Dimension((int) bounds.getWidth(), (int) bounds.getHeight()); } public static boolean isStringEmpty(String s) { return (s == null || s.length() == 0); } }