How can I center the text of a drawString in Java? I want it to that it can be centered along the screen dynamically, whether I change the height and width of the box or not. I found this codebut I don't know how to use it. can someone explain?
Asked
Active
Viewed 2,491 times
-3
-
The answer in that post has some well documented method. – Trevi Awater Sep 30 '15 at 06:47
-
1What part of *"I don't know how to use it"* are you stuck on – MadProgrammer Sep 30 '15 at 06:48
-
`but I don't know how to use it. can someone explain?`. 1st copy the code, 2nd paste the code, 3rd see what happens when you compile it, 4th analyze it, if you're stuck and have an error in it, then post **your** [MCVE](http://stackoverflow.com/help/mcve) – Frakcool Sep 30 '15 at 06:48
1 Answers
3
Horizontally...
String text = "...";
Graphics2D g2d = (Graphics2D)g.create();
FontMetrics fm = g2d.getFontMetrics();
int x = (getWidth() - fm.stringWidth(text)) / 2;
Vertically...
String text = "...";
Graphics2D g2d = (Graphics2D)g.create();
FontMetrics fm = g2d.getFontMetrics();
int y = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();
Also demonstrated here
Also have a look at 2D Graphics and Working with Text APIs

Community
- 1
- 1

MadProgrammer
- 343,457
- 22
- 230
- 366