Reputation: 11
I'm trying to find different ways of centering text within a main menu that I'm trying to create, but all the ways that I've tried centers the string from the first letter. Is there any way of determining the length of the string passed in and then work out the center from that?
Upvotes: 1
Views: 853
Reputation: 51565
I wrote this a while back.
/**
* This method centers a <code>String</code> in
* a bounding <code>Rectangle</code>.
* @param g - The <code>Graphics</code> instance.
* @param r - The bounding <code>Rectangle</code>.
* @param s - The <code>String</code> to center in the
* bounding rectangle.
* @param font - The display font of the <code>String</code>
*
* @see java.awt.Graphics
* @see java.awt.Rectangle
* @see java.lang.String
*/
public void centerString(Graphics g, Rectangle r, String s,
Font font) {
FontRenderContext frc =
new FontRenderContext(null, true, true);
Rectangle2D r2D = font.getStringBounds(s, frc);
int rWidth = (int) Math.round(r2D.getWidth());
int rHeight = (int) Math.round(r2D.getHeight());
int rX = (int) Math.round(r2D.getX());
int rY = (int) Math.round(r2D.getY());
int a = (r.width / 2) - (rWidth / 2) - rX;
int b = (r.height / 2) - (rHeight / 2) - rY;
g.setFont(font);
g.drawString(s, r.x + a, r.y + b);
}
Upvotes: 0
Reputation: 481
If you're using a JLabel, overload the constructor using a center attribute. example:
label = new JLabel("insert text here");
to
label = new JLabel("insert text here", SwingConstants.CENTER);
Upvotes: 0