Draw Text in Middle of the Screen

5.8k views Asked by At

I'm trying to draw text in the middle of my JFrame window, and it's off by a little bit.

Here's what I've tried :

FontMetrics fontMetrics = g.getFontMetrics(font);

// draw title
g.setColor(Color.WHITE);
g.setFont(font);
int titleLen = fontMetrics.stringWidth("Level 1 Over!");
g.drawString("Level 1 Over!", (screenWidth / 2) - (titleLen / 2), 80);
4

There are 4 answers

1
JavaDM On

With your code, the String starts at the very middle. try this:

FontMetrics fontMetrics = g.getFontMetrics(font);

// draw title
g.setColor(Color.WHITE);
g.setFont(font);
int titleLen = fontMetrics.stringWidth("Level 1 Over!");
g.drawString("Level 1 Over!", (screenWidth / 2) - (titleLen), 80);
1
Kumar Vivek Mitra On

- Use Toolkit to get the height and width of the screen.

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();

- Then set the text in the middle of the screen.

g.drawString("Level 1 Over!",(width/2),(height/2));
0
Gilbert Le Blanc On

I've found that the TextLayout class gives better dimensions for the String than FontMetrics.

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);

    if (font == null) {
        return;
    }

    Graphics2D g2d = (Graphics2D) g;
    FontRenderContext frc = g2d.getFontRenderContext();
    TextLayout layout = new TextLayout(sampleString, font, frc);
    Rectangle2D bounds = layout.getBounds();

    int width = (int) Math.round(bounds.getWidth());
    int height = (int) Math.round(bounds.getHeight());
    int x = (getWidth() - width) / 2;
    int y = height + (getHeight() - height) / 2;

    layout.draw(g2d, (float) x, (float) y);
}
0
XMB5 On

I know this is old but this worked for me...

public void drawCenter ( String m , Font font )
    FontMetrics fm = g.getFontMetrics ( font );
    int sw = fm.stringWidth ( m );
    g.setFont ( font );
    g.setColor ( Color.BLACK );
    g.drawString ( m , ( frame.getWidth() + sw ) / 2 - sw , frame.getHeight() / 2 );
}

In this example g is Graphics2D but I think it works with Graphics also