Here you can find the source of drawStringCentered(Graphics graphics, String string, Rectangle area)
public static void drawStringCentered(Graphics graphics, String string, Rectangle area)
//package com.java2s; /*//from w ww .j av a2 s. com * File: GraphicsHelper.java * Copyright (c) 2004-2007 Peter Kliem (Peter.Kliem@jaret.de) * A commercial license is available, see http://www.jaret.de. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html */ import java.awt.Graphics; import java.awt.Rectangle; import java.awt.geom.Rectangle2D; public class Main { public static void drawStringCentered(Graphics graphics, String string, int left, int right, int y) { Rectangle2D rect = graphics.getFontMetrics().getStringBounds(string, graphics); int width = right - left; int xx = (int) ((width - rect.getWidth()) / 2); graphics.drawString(string, xx, y); } /** * @param graphics graphics to use * @param string string to render * @param x center x * @param y basey */ public static void drawStringCentered(Graphics graphics, String string, int x, int y) { Rectangle2D rect = graphics.getFontMetrics().getStringBounds(string, graphics); int xx = x - (int) ((rect.getWidth()) / 2); graphics.drawString(string, xx, y); } public static void drawStringCentered(Graphics graphics, String string, Rectangle area) { Rectangle2D rect = graphics.getFontMetrics().getStringBounds(string, graphics); int xx = area.x + area.width / 2 - (int) ((rect.getWidth()) / 2); int yy = (int) (area.y + area.height / 2 + (rect.getHeight() / 2)); graphics.drawString(string, xx, yy); } }