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?
Asked
Active
Viewed 807 times
0
-
Do you mean visually centering, which would depend on the typeface in which the text is displayed? Or do you mean centered with an equal number of characters to left and right of center? – shoover Jul 21 '15 at 22:31
-
1Equal amount of characters left and right. – Jake Roper Jul 21 '15 at 22:35
-
You mean something like [this](http://stackoverflow.com/questions/14284754/java-center-text-in-rectangle/14287270#14287270) or [this](http://stackoverflow.com/questions/18565066/centering-string-in-panel/18565132#18565132) – MadProgrammer Jul 21 '15 at 22:36
2 Answers
1
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);

sBourne
- 483
- 1
- 5
- 17
-
I have a string variable that is passed into drawString, which is then drawn onto the screen. No labels involved. Any other ideas? I'll try your label idea though just in case. – Jake Roper Jul 21 '15 at 22:31
-
Hm. Not entirely sure how to get around the calculate length hack then. Maybe try drawing into the JLabel and center that. – sBourne Jul 21 '15 at 22:38
-
@JakeRoper, `No labels involved.` - that is the point. Why are you not use a JLabel and the appropriate layout manager. Then all the work of displaying the text and centering it will be done by Swing and the layout manager. – camickr Jul 22 '15 at 01:10
0
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);
}

Gilbert Le Blanc
- 50,182
- 6
- 67
- 111