This week's giveaway is in the JDBC forum.
We're giving away four copies of Java Database Connections & Transactions (e-book only) and have Marco Behler on-line!
See this thread for details.
Win a copy of Java Database Connections & Transactions (e-book only) this week in the JDBC forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Knute Snortum
  • Paul Clapham
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Frits Walraven
Bartenders:
  • Ganesh Patekar
  • Tim Holloway
  • salvin francis

Size of String in Pixels from JTextField  RSS feed

 
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • 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
 
Never trust an airline that limits their passengers to one carry on iguana. Put this tiny ad in your shoe:
how do I do my own kindle-like thing - without amazon
https://coderanch.com/t/711421/engineering/kindle-amazon
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!