Here you can find the source of drawText(Graphics2D graphics, Font font, Dimension2D dimension, String text)
Parameter | Description |
---|---|
graphics | graphics context for drawing. |
font | font used for drawing the characters |
dimension | dimension in which to center the text. |
text | unicode characters to be drawn. |
public static void drawText(Graphics2D graphics, Font font, Dimension2D dimension, String text)
//package com.java2s; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.geom.Dimension2D; import java.awt.geom.Rectangle2D; public class Main { /**//from w ww . j ava2s. c o m * draws the given unicode characters horizontally using the specified font. * note: this method handles standard unicode characters as well as the supplementary unicode characters in the range 0x010000 - 0x10FFFF. * <br/><br/> * @param graphics graphics context for drawing. * @param font font used for drawing the characters * @param dimension dimension in which to center the text. * @param text unicode characters to be drawn. */ public static void drawText(Graphics2D graphics, Font font, Dimension2D dimension, String text) { // determine the extent of the text box FontMetrics metrics = graphics.getFontMetrics(font); Rectangle2D bounds2d = metrics.getStringBounds(text, graphics); // determine the extent of the text double x = (dimension.getWidth() - bounds2d.getWidth()) / 2.0; double y = bounds2d.getHeight() / 2.0 - metrics.getLeading(); // draw the text graphics.setFont(font); graphics.drawString(text, (float) x, (float) y); } }