Java Graphics Draw String drawTextCenter(Graphics2D g2, String str, int x, int y)

Here you can find the source of drawTextCenter(Graphics2D g2, String str, int x, int y)

Description

draw Text Center

License

Open Source License

Declaration

public static void drawTextCenter(Graphics2D g2, String str, int x,
            int y) 

Method Source Code

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

import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;

public class Main {
    public static void drawTextCenter(Graphics2D g2, String str, int x,
            int y) {
        int strWidth = getStringWidth(g2, str);
        drawText(g2, str, x - strWidth / 2, y
                + g2.getFontMetrics().getHeight() / 2);
    }//from ww  w .  ja  va 2 s  .  c om

    public static int getStringWidth(Graphics2D g2, final String str) {
        Rectangle2D bounds = g2.getFont().getStringBounds(str,
                g2.getFontRenderContext());
        return (int) bounds.getWidth();
    }

    public static void drawText(Graphics2D g2, String str, int x, int y) {
        g2.translate(x, y);
        g2.drawString(str, 0, 0);
        g2.translate(-x, -y);
    }
}

Related

  1. drawRotatedShape(final Shape shape, final Graphics2D g2, final float x, final float y, final double angle)
  2. drawScaleLabel(Graphics g, String label, int x, int y, boolean yAxisP)
  3. drawSystemNameLabel(Graphics2D g, String sysName, Color color, double safetyOffset, boolean isLocationKnownUpToDate)
  4. drawText(Graphics graphics, int x, int y, String text)
  5. drawText(Graphics2D graphics, Font font, Dimension2D dimension, String text)
  6. drawTextInBoundedArea(Graphics2D g2d, int x1, int y1, int x2, int y2, String text)
  7. drawTuplet(Graphics g, int x, int y, int x2, int y2, int bi, String s1, String s2)
  8. drawUnderlineCharAt(Graphics g, String text, int underlinedIndex, int x, int y)
  9. drawVerticalText(Graphics2D graphics, Font font, Dimension2D dimension, String text)