Java Graphics Draw String drawCentered(Graphics g, String text, Point p)

Here you can find the source of drawCentered(Graphics g, String text, Point p)

Description

draw Centered

License

Open Source License

Declaration

public static final void drawCentered(Graphics g, String text, Point p) 

Method Source Code

//package com.java2s;
/*//from ww w . ja va  2  s.  c  om
 * This file is part of the Jose Project
 * see http://jose-chess.sourceforge.net/
 * (c) 2002-2006 Peter Sch?fer
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 */

import java.awt.*;

public class Main {
    public static final void drawCentered(Graphics g, String text, Point p) {
        drawCentered(g, text, p.x, p.y);
    }

    public static void drawCentered(Graphics g, String text, int x, int y) {
        FontMetrics fmx = g.getFontMetrics();
        Rectangle bounds = new Rectangle(0, 0, fmx.stringWidth(text),
                fmx.getAscent() - fmx.getLeading() - fmx.getDescent());
        /*      this calculation is not quite correct, of course
        but it eliminates the space above the characters
        */
        //   center bounds on box;
        centerOn(bounds, x, y);
        g.drawString(text, bounds.x, bounds.y + bounds.height);
    }

    public static final void centerOn(Rectangle a, Point p) {
        a.x = p.x - a.width / 2;
        a.y = p.y - a.height / 2;
    }

    public static final void centerOn(Rectangle a, int x, int y) {
        a.x = x - a.width / 2;
        a.y = y - a.height / 2;
    }
}

Related

  1. centerString(Graphics g, String s, Font f, int w0, int w, int h)
  2. centerStringX(String s, int w, Graphics2D g2d)
  3. centerStringY(String s, int h, Graphics2D g2d)
  4. drawCenteredChar(Graphics g, char[] chars, int x, int y, int w, int h)
  5. drawCenteredString(Graphics g, Rectangle rect, String str)
  6. drawCenteredString(Graphics g, String str, int x, int y)
  7. drawCenteredString(String s, Graphics g, int x, int y)