• 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

Size of String in Pixels from JTextField

 
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi there

I have to take the text from a JTextField and find out what the size of the String is in pixels.

I see that from Graphics I could get FontMetrics and that would be the solution, but in this instance, I can't get a handle to the graphics object as it is not yet displayed. I've also looked at Toolkit.getFontMetrics but that gives a whole long winded thing about being Deprecated.

Can anyone give any suggestions for this?

Many kind regards,
Rachel
 
Ranch Hand
Posts: 1535
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here's a demo that explores font properties. I put everything inside the paintComponent method for the demo but you can just as easily do the computations outside, ie, without the graphics context — check out the three–argument constructor in the FontRenderContext api. You can use null for the AffineTransform argument.

Also check the Font getStringBounds and LineMetrics getHeight methods for information on what is included in the height. I left out the leading in the demo. You can experiment with the height factors to get the results you need; endless fun...
 
Rachel Swailes
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Craig!

Thanks a bunch, I haven't had a play with it yet, but it looks to be just what I need!

Cheers,
Rachel
 
Or we might never have existed at all. Freaky. So we should cherish everything. Even this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic