Draws a string centered at a certain x-coordinate - Java 2D Graphics

Java examples for 2D Graphics:Text

Description

Draws a string centered at a certain x-coordinate

Demo Code


//package com.java2s;
import java.awt.FontMetrics;
import java.awt.Graphics;

public class Main {
    /**//from w  w w . j  a v  a 2  s.c o  m
     * Draws a string centered at a certain x-coordinate
     * 
     * @param g Graphics instance
     * @param text The string to draw.
     * @param baseX The x-coordinate upon which to center.
     * @param baseY The y-coordinate at which to draw the baseline.
     */
    public static void drawCenteredString(Graphics g, String text,
            int baseX, int baseY) {
        FontMetrics metrics = g.getFontMetrics(g.getFont());
        int width = metrics.stringWidth(text);

        /* OSX bug here - the letters will render backwards if rotated. The commented-out call below was
         * meant to get around this, but instead opened up several gallons of worms. So, for now, OSX
         * can have its bug.
         */
        //drawBufferedString(g, text, baseX - width/2, baseY, obs);
        g.drawString(text, baseX - width / 2, baseY);
    }
}

Related Tutorials