Here you can find the source of drawStringCentered(Graphics g, String str, int x, int y, int width, int height)
Parameter | Description |
---|---|
g | the graphics context. |
str | the string. |
x | the bounding x position. |
y | the bounding y position. |
width | the bounding width. |
height | the bounding height. |
public static void drawStringCentered(Graphics g, String str, int x, int y, int width, int height)
//package com.java2s; import java.awt.FontMetrics; import java.awt.Graphics; public class Main { /**/*from www . j ava2s . c o m*/ * Draw a string centered within a rectangle. The string is drawn using the graphics context's * current font and color. * * @param g the graphics context. * @param str the string. * @param x the bounding x position. * @param y the bounding y position. * @param width the bounding width. * @param height the bounding height. */ public static void drawStringCentered(Graphics g, String str, int x, int y, int width, int height) { FontMetrics fm = g.getFontMetrics(g.getFont()); int xpos = x + ((width - fm.stringWidth(str)) / 2); int ypos = y + ((height + fm.getAscent()) / 2); g.drawString(str, xpos, ypos); } }