Here you can find the source of drawText(Graphics graphics, int x, int y, String text)
Parameter | Description |
---|---|
graphics | A graphics context. |
x | The x coordinate. |
y | The y coordinate. |
text | The text to draw. |
public static Rectangle drawText(Graphics graphics, int x, int y, String text)
//package com.java2s; import java.awt.*; import java.awt.geom.Rectangle2D; public class Main { /**/*from w ww .j a v a2 s . com*/ * Draw a text to a graphics context. The specified point is the upper left corner of the text * bounds which are calculated from the text by calling {@link #getTextBounds(java.awt.Graphics, * String)}. The method returns the text bounds that have been used for drawing in screen * coordinates. This means the upper left corner of the returned rectangle is the point * specified when calling the method. * * @param graphics A graphics context. * @param x The x coordinate. * @param y The y coordinate. * @param text The text to draw. * * @return The text bounds of the text drawn on the screen. */ public static Rectangle drawText(Graphics graphics, int x, int y, String text) { Rectangle bounds = getTextBounds(graphics, text); graphics.drawString(text, x + bounds.x, y + bounds.y); bounds.y = 0; bounds.translate(x, y); return bounds; } /** * 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()); } }