Here you can find the source of getTextBounds(Graphics graphics, String text)
Parameter | Description |
---|---|
graphics | A graphics context. |
text | A text. |
public static Rectangle getTextBounds(Graphics graphics, String text)
//package com.java2s; import java.awt.*; import java.awt.geom.Rectangle2D; public class Main { /**//from www . j a v a 2s . c o m * Get the bounds for drawing the specified text in the specified graphics context. The bounds * returned contain the correct width and height for the text. The x position is always set to 0 * and the y position specifies the maximum text ascend. So drawing the text with the x and y * coordinate from the returned rectangle makes the text appear in the upper left corner of the * target context. * * @param graphics A graphics context. * @param text A text. * * @return The bounds as described above. */ public static Rectangle getTextBounds(Graphics graphics, String text) { FontMetrics metrics = graphics.getFontMetrics(); Rectangle2D textBounds = metrics.getStringBounds(text, graphics); int textAscend = metrics.getMaxAscent(); return new Rectangle(0, textAscend, (int) textBounds.getWidth(), textAscend + metrics.getMaxDescent()); } }