File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes Width of a String in pixels Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide 1Z0-808 this week in the OCAJP forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Width of a String in pixels" Watch "Width of a String in pixels" New topic

Width of a String in pixels

D N Taylor

Joined: Oct 06, 2004
Posts: 5
I'm trying to draw a string to the screen but I need it to be right-justified, so the last character of the string is always at exactly the same position on the screen.

But the value of the String itself can be any value and any length, e.g. it could be "hello" or it could be "what time is it?". How do I ensure that it always displays at the right place on the screen every time?

The biggest problem is, the font I'm using is not a monospace font - so all the characters are different widths. It would be easy otherwise!

I'm thinking maybe the best way to tackle this is to put the string into a Label, set it to the same font, and then measure the physical width of the label in pixels. But I'm not sure how to do this exactly?!

Any help is much appreciated!

D Taylor
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24189

On your Graphics object (i.e., in your paint method) call getFontMetrics(), with no arguments for the default font or passing the appropriate Font object. Then on the FontMetrics object that you get back, call stringWidth(), passing your String as an argument; this returns the width in pixels.

[Jess in Action][AskingGoodQuestions]
D N Taylor

Joined: Oct 06, 2004
Posts: 5
Excellent stuff! I will try this when I get home.

Thank you very much.

D Taylor
wood burning stoves
subject: Width of a String in pixels