Reputation: 1326
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);
Upvotes: 2
Views: 5901
Reputation: 1602
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
Upvotes: 1
Reputation: 51445
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);
}
Upvotes: 3
Reputation: 33534
- 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));
Upvotes: 0
Reputation: 851
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);
Upvotes: 2