javaawtfontmetrics

Java - Centering Text (on a Canvas)


thanks for checking out my question.

I am working a menu for the game that I'm making, and I want to center the game's title on the main menu. I've looked at several questions here on Stack Overflow, but couldn't find an answer.

Problem

The problem that I'm having is that whenever I call my centerString() method, it puts it in the center of the y-axis, but not of the x-axis. What am I doing wrong here?

Code

Method code

private void centerString(String txt, int width, int height, Graphics g, Font font) {
        FontMetrics metrics = g.getFontMetrics();
        int x = (width - metrics.stringWidth(txt)) / 2;
        int y = (metrics.getAscent() + (height - (metrics.getAscent() + metrics.getDescent())) / 2);
        g.setFont(font);
        g.drawString(txt, x, y);
}

Where it's called

final Font fnt = new Font("Arial", Font.BOLD, 36);
centerString("ThatMarioEngine", toInt(screenSize.getWidth()), toInt(screenSize.getHeight()), g, fnt);

Solution

  • I have fixed the issue by making using the windows size, instead of the screen size. The centering issue was fixed by putting g.setFont(font); before I get the FontMetrics.