Java Draw Centered drawCenterString(Graphics g, Point p, String text)

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

Description

Draws a centered string

License

Open Source License

Parameter

Parameter Description
g Grpahics object
p Location of string
text Text to draw

Declaration

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

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;

import java.awt.Point;

public class Main {
    /**/*from  www.j  a  v  a 2s  .  co  m*/
     * Draws a centered string
     * 
     * @param g
     *            Grpahics object
     * @param p
     *            Location of string
     * @param text
     *            Text to draw
     */
    public static void drawCenterString(Graphics g, Point p, String text) {
        Graphics2D g2d = (Graphics2D) g;

        // Get the FontMetrics
        FontMetrics metrics = g2d.getFontMetrics();
        int x = p.x - (metrics.stringWidth(text) / 2);
        // Determine the Y coordinate for the text
        int y = p.y + (int) (metrics.getHeight() / 3);

        g2d.drawString(text, x, y);
    }
}

Related

  1. drawCenterCircle(Graphics2D g, Point p, int radius)
  2. drawCenteredCircle(Graphics2D g, int x, int y, int r)
  3. drawCentred(Graphics2D g2, String message, Rectangle2D box)
  4. drawCentredText(Graphics g, String str, int x, int y, int width, int height)
  5. drawEllipseOld(Graphics g, double xCenter, double yCenter, double semiMA, double semiMI, double angle)
  6. drawStringCenter(Graphics2D g, String text, Rectangle rect, int fontHeight, Color c)