The list of methods to do Draw Centered are organized into topic(s).
void
drawCenterString(Graphics g, Point p, String text) Draws a centered string
Graphics2D g2d = (Graphics2D) g;
FontMetrics metrics = g2d.getFontMetrics();
int x = p.x - (metrics.stringWidth(text) / 2);
int y = p.y + (int) (metrics.getHeight() / 3);
g2d.drawString(text, x, y);
void
drawCentred(Graphics2D g2, String message, Rectangle2D box) Draws a string centred in the given box.
FontMetrics metrics = g2.getFontMetrics();
Rectangle2D stringBounds = g2.getFont().getStringBounds(message, g2.getFontRenderContext());
float x = (float) (box.getX() + (box.getWidth() - stringBounds.getWidth()) / 2.0);
float y = (float) (box.getY() + (box.getHeight() + metrics.getAscent() - metrics.getDescent()) / 2.0);
g2.drawString(message, x, y);
void
drawCentredText(Graphics g, String str, int x, int y, int width, int height) Draw a string at a given location on screen centered in a given rectangle.
Left justifies the string if it is too long to fit all of the string inside the rectangle.
FontMetrics fm = g.getFontMetrics();
Shape oldClip = g.getClip();
g.clipRect(x, y, width, height);
int xOffset = (width - fm.stringWidth(str)) / 2;
if (xOffset < 0) {
xOffset = 0;
int yOffset = fm.getAscent() + ((height - fm.getAscent() - fm.getDescent()) / 2);
...
void
drawStringCenter(Object o, Rectangle r, Font f, Graphics2D g) draw String Center
int w = r.x + (r.width - g.getFontMetrics(f).stringWidth(o.toString())) / 2;
int h = r.y + g.getFontMetrics(f).getAscent();
h -= g.getFontMetrics(f).getDescent();
h += (r.height - f.getSize()) / 2;
g.setFont(f);
g.drawString(o.toString(), w, h);
void
drawStringCentered(final Graphics2D g2d, final Dimension dim, final String drawString, final int fontSize) Draw a given String to a graphic object centered
Rectangle2D bounds;
Object KEY_ANTIALIASING_before = g2d.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
Object KEY_TEXT_ANTIALIASING_before = g2d.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
float posx = 0, posy = 0;
g2d.setFont(g2d.getFont().deriveFont(Font.PLAIN, fontSize));
FontRenderContext frc = g2d.getFontRenderContext();
...