Java examples for 2D Graphics:Text
draw String Centered
//package com.java2s; import java.awt.*; import java.awt.geom.Rectangle2D; public class Main { /**//from w ww. j a va2s . co m * * @param text String to paint * @param font Font type of string * @param rect Rectangle string will be in * @param color Color of the string * @param g Graphics which will paint string */ public static void drawStringCentered(String text, Font font, Rectangle rect, Color color, Graphics g) { g.setFont(font); g.setColor(color); FontMetrics fm = g.getFontMetrics(); Rectangle2D stringRect = fm.getStringBounds(text, g); int x = (int) (rect.getCenterX() - stringRect.getWidth() / 2.0D); int y = (int) (rect.getCenterY() + rect.getHeight() / 3.0D); g.drawString(text, x, y); } }