• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Width of a String in pixels

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
D N Taylor
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Excellent stuff! I will try this when I get home.

Thank you very much.


D Taylor
 
reply
    Bookmark Topic Watch Topic
  • New Topic