Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Size of String in Pixels from JTextField  RSS feed

 
Rachel Swailes
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
 
Craig Wood
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
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!