Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Calculating pixels of a String 1

Status
Not open for further replies.

bernardlejour

IS-IT--Management
Oct 10, 2002
2
CA
I am new to the language. I have written an applet that displays a vertical scrolling text window. I want the text displayed to be centered. I use the drawString instruction to show the text which has multiple lines and I loop through. My problem is the centering of each line of text. I have to instruct drawString x and y coordinates but I presently have to figure it out manually by trial and error. Leaving blanks in front does not solve the problem because the blanks do not take the same space as regular characters.

Is there a way to center the text (calculate the number of pixels used by a given string) or is there a better method to achieve what I want to do?
 
You have to use the Graphics method getFontMetrics() to get the FontMetrics object of the current Font. Then you use the getStringWidth(String s) method in FontMetrics. Good luck!

example:
Code:
FontMetrics fm = g.getFontMetrics();
int width = fm.getStringWidth(text);
regards,
Blaxo
 
Thank you very much for the advice. Looking up the SUN site for info about FontMetrics,I found an example that was doing exactly what I needed.

Again, thank you for your help.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top