Java Draw Centered drawStringCentered(Graphics g, String str, int x, int y, int width, int height)

Here you can find the source of drawStringCentered(Graphics g, String str, int x, int y, int width, int height)

Description

Draw a string centered within a rectangle.

License

Open Source License

Parameter

Parameter Description
g the graphics context.
str the string.
x the bounding x position.
y the bounding y position.
width the bounding width.
height the bounding height.

Declaration

public static void drawStringCentered(Graphics g, String str, int x, int y, int width, int height) 

Method Source Code

//package com.java2s;

import java.awt.FontMetrics;

import java.awt.Graphics;

public class Main {
    /**/*from  www  .  j ava2s  . c o  m*/
     * Draw a string centered within a rectangle.  The string is drawn using the graphics context's
     * current font and color.
     *
     * @param g the graphics context.
     * @param str the string.
     * @param x the bounding x position.
     * @param y the bounding y position.
     * @param width the bounding width.
     * @param height the bounding height.
     */
    public static void drawStringCentered(Graphics g, String str, int x, int y, int width, int height) {
        FontMetrics fm = g.getFontMetrics(g.getFont());
        int xpos = x + ((width - fm.stringWidth(str)) / 2);
        int ypos = y + ((height + fm.getAscent()) / 2);
        g.drawString(str, xpos, ypos);
    }
}

Related

  1. drawCentredText(Graphics g, String str, int x, int y, int width, int height)
  2. drawEllipseOld(Graphics g, double xCenter, double yCenter, double semiMA, double semiMI, double angle)
  3. drawStringCenter(Graphics2D g, String text, Rectangle rect, int fontHeight, Color c)
  4. drawStringCenter(Object o, Rectangle r, Font f, Graphics2D g)
  5. drawStringCentered(final Graphics2D g2d, final Dimension dim, final String drawString, final int fontSize)
  6. drawStringCentered(Graphics graphics, String string, Rectangle area)
  7. drawStringCentered(Graphics2D g, String text, int x, int y, int fontHeight, Color c)
  8. drawVerticallyCenteredText(String text, int margin, Rectangle rect, Graphics g2D, boolean rightJustify)