0

I am drawing 2 Strings which the one include my Name, Middle-name, Surname and the other my Country i am creating them in a paint Component which is located in a Center panel, however, I have tried many different ways and calculations to center that String but no one of them is working correctly with accuracy is their an accurate way ? this is an example of calculations that i have tried so far

posX=((getWidth()-fm.stringWidth(phrase))/2);
posY= ((getHeight()-fm.getHeight())/2);  
  • [For example](https://stackoverflow.com/questions/32859509/how-to-center-a-drawstring-in-java/32859632#32859632), [example](https://stackoverflow.com/questions/18565066/centering-string-in-panel/18565132#18565132) and [example](https://stackoverflow.com/questions/14284754/java-center-text-in-rectangle/14287270#14287270) – MadProgrammer Nov 07 '17 at 21:08
  • *"however, I have tried many different ways and calculations to center that String but no one of them is working correctly with accuracy is their an accurate way ?"* - I'd be nice if you could provide a demonstration of it "not working" and contracts that with what you are attempting to achieve – MadProgrammer Nov 07 '17 at 21:11
  • 1
    Why are you doing custom painting? Use JLabels and an appropriate layout manager. The layout manager will look after centering all the components. – camickr Nov 07 '17 at 21:45

1 Answers1

1

Because text is rendered from the baseline up, you need to adjust the y position to take that into account:

posY = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();

Otherwise you're centring the text about the baseline, instead of "absolutely"

This is demonstrated in this example

You should also have a look at Font Concepts for more details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366