Here you can find the source of drawVerticallyCenteredText(String text, int margin, Rectangle rect, Graphics g2D, boolean rightJustify)
public static void drawVerticallyCenteredText(String text, int margin, Rectangle rect, Graphics g2D, boolean rightJustify)
//package com.java2s; /*// w w w. java 2 s . co m * Copyright (c) 2007-2012 The Broad Institute, Inc. * SOFTWARE COPYRIGHT NOTICE * This software and its documentation are the copyright of the Broad Institute, Inc. All rights are reserved. * * This software is supplied without any warranty or guaranteed support whatsoever. The Broad Institute is not responsible for its use, misuse, or functionality. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), * Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php. */ import java.awt.*; import java.awt.geom.Rectangle2D; public class Main { public static void drawVerticallyCenteredText(String text, int margin, Rectangle rect, Graphics g2D, boolean rightJustify) { drawVerticallyCenteredText(text, margin, rect, g2D, rightJustify, false); } /** * Draw a block of text centered vertically in the rectangle * * @param text * @param rect * @param g2D */ public static void drawVerticallyCenteredText(String text, int margin, Rectangle rect, Graphics g2D, boolean rightJustify, boolean clear) { FontMetrics fontMetrics = g2D.getFontMetrics(); Rectangle2D textBounds = fontMetrics.getStringBounds(text, g2D); int yOffset = (int) ((rect.getHeight() - textBounds.getHeight()) / 2); int yPos = (rect.y + rect.height) - yOffset - (int) (textBounds.getHeight() / 4); if (clear) { int h = 2 * (int) textBounds.getHeight(); //Color c = g2D.getColor(); //Globals.isHeadless(); //g2D.setColor(Globals.VERY_LIGHT_GREY); int y = Math.max(rect.y, yPos - h); int h2 = Math.min(rect.height, 2 * h); g2D.clearRect(rect.x, y, rect.width, h2); //g2D.setColor(c); } if (rightJustify) { drawRightJustifiedText(text, rect.x + rect.width - margin, yPos, g2D); } else { g2D.drawString(text, margin, yPos); } } /** * Draw a block of text right justified to the given location * * @param text * @param right * @param y * @param g */ public static void drawRightJustifiedText(String text, int right, int y, Graphics g) { FontMetrics fontMetrics = g.getFontMetrics(); Rectangle2D textBounds = fontMetrics.getStringBounds(text, g); int x = right - (int) textBounds.getWidth(); g.drawString(text, x, y); } }