Here you can find the source of drawString(Graphics2D graphics, String text, double x, double y, boolean centerHorizontal, boolean centerVertical, Color backgroundColor)
public static Rectangle2D drawString(Graphics2D graphics, String text, double x, double y, boolean centerHorizontal, boolean centerVertical, Color backgroundColor)
//package com.java2s; //License from project: Open Source License import java.awt.Color; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; public class Main { public static Rectangle2D drawString(Graphics2D graphics, String text, double x, double y, boolean centerHorizontal, boolean centerVertical, Color backgroundColor) { return drawString(graphics, text, x, y, centerHorizontal, centerVertical, backgroundColor, Color.BLACK); }//w w w . j av a 2 s.c om public static Rectangle2D drawString(Graphics2D graphics, String text, double x, double y, boolean centerHorizontal, boolean centerVertical, Color backgroundColor, Color textColor) { AffineTransform transform = graphics.getTransform(); Point2D source = new Point2D.Double(x, y); Point2D destination = new Point2D.Double(); transform.transform(source, destination); try { transform.invert(); } catch (NoninvertibleTransformException e1) { e1.printStackTrace(); } graphics.transform(transform); Rectangle2D r = graphics.getFontMetrics().getStringBounds(text, graphics); int xPosition = Math.round((float) (destination.getX() - (centerHorizontal ? r.getWidth() / 2.0f - 1 : 0))); int yPosition = Math .round((float) (destination.getY() + (centerVertical ? r.getHeight() / 2.0f - 1.5 : 0))); if (backgroundColor != null) { graphics.setColor(backgroundColor); int width = (int) (r.getMaxY() - r.getMinY()); int height = (int) (r.getMaxX() - r.getMinX()); graphics.fillRect(xPosition, yPosition - width, height, width); } Rectangle2D boundingRectangle = new Rectangle2D.Double(xPosition, yPosition - r.getHeight(), r.getWidth(), r.getHeight()); transform.createTransformedShape(boundingRectangle); graphics.setColor(textColor); graphics.drawString(text, xPosition, yPosition); try { transform.invert(); } catch (NoninvertibleTransformException e1) { e1.printStackTrace(); } graphics.transform(transform); return boundingRectangle; } }