Here you can find the source of drawTextCenter(Graphics2D g2, String str, int x, int y)
public static void drawTextCenter(Graphics2D g2, String str, int x, int y)
//package com.java2s; //License from project: Open Source License import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; public class Main { public static void drawTextCenter(Graphics2D g2, String str, int x, int y) { int strWidth = getStringWidth(g2, str); drawText(g2, str, x - strWidth / 2, y + g2.getFontMetrics().getHeight() / 2); }//from ww w . ja va 2 s . c om public static int getStringWidth(Graphics2D g2, final String str) { Rectangle2D bounds = g2.getFont().getStringBounds(str, g2.getFontRenderContext()); return (int) bounds.getWidth(); } public static void drawText(Graphics2D g2, String str, int x, int y) { g2.translate(x, y); g2.drawString(str, 0, 0); g2.translate(-x, -y); } }