Java Utililty Methods Graphics Draw String

List of utility methods to do Graphics Draw String

Description

The list of methods to do Graphics Draw String are organized into topic(s).

Method

voidcenterString(Graphics g, String s, Font f, int w0, int w, int h)
center String
int p, sw;
g.setFont(f);
sw = g.getFontMetrics(f).stringWidth(s);
g.drawString(s, w0 + (w - sw) / 2, h);
intcenterStringX(String s, int w, Graphics2D g2d)
center String X
FontMetrics fm = g2d.getFontMetrics(g2d.getFont());
return (w - fm.stringWidth(s)) / 2;
intcenterStringY(String s, int h, Graphics2D g2d)
center String Y
FontRenderContext frc = g2d.getFontRenderContext();
GlyphVector gv = g2d.getFont().createGlyphVector(frc, s);
Rectangle vb = gv.getVisualBounds().getBounds();
return h / 2 - vb.height / 2 - vb.y;
voiddrawCentered(Graphics g, String text, Point p)
draw Centered
drawCentered(g, text, p.x, p.y);
voiddrawCenteredChar(Graphics g, char[] chars, int x, int y, int w, int h)
draw Centered Char
FontMetrics fm = g.getFontMetrics();
int msg_width = fm.charsWidth(chars, 0, 1);
int ascent = fm.getMaxAscent();
int descent = fm.getMaxDescent();
int msgX = x + w / 2 - msg_width / 2;
int msgY = y + h / 2 - descent / 2 + ascent / 2;
g.drawChars(chars, 0, 1, msgX, msgY);
voiddrawCenteredString(Graphics g, Rectangle rect, String str)
Draws a string inside a box
Graphics2D g2d = (Graphics2D) g;
FontMetrics fm = g2d.getFontMetrics();
Rectangle2D r = fm.getStringBounds(str, g2d);
int dx = (int) ((rect.getWidth() - (int) r.getWidth()) / 2);
int dy = (int) ((rect.getHeight() - (int) r.getHeight()) / 2 + fm.getAscent());
g.drawString(str, rect.x + dx, rect.y + dy);
voiddrawCenteredString(Graphics g, String str, int x, int y)
draw Centered String
FontMetrics fm = g.getFontMetrics();
int strW = fm.stringWidth(str), strH = fm.getHeight();
x -= strW / 2;
y += strH / 5;
g.drawString(str, x, y);
voiddrawCenteredString(String s, Graphics g, int x, int y)
Draws the given String, centered at (x,y), using the given graphics context.
((Graphics2D) g).addRenderingHints(hints);
FontMetrics fm = g.getFontMetrics();
int ht = fm.getAscent() + fm.getDescent();
int width = fm.stringWidth(s);
g.drawString(s, x - width / 2, y + (fm.getAscent() - ht / 2));
voiddrawCenteredText(Graphics2D g, String text, int x, int y, float align_x, float align_y, float font_size)
Draw text centered on a point
drawCenteredText(g, text, x, y, 0, 0, align_x, align_y, font_size);
voiddrawCenteredText(java.awt.Graphics g, String s, java.awt.Rectangle rect)
draw Centered Text
drawCenteredText(g, s, rect.x, rect.y, rect.width, rect.height);