Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Number of characters per number of pixels

 
Richard Everhart
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need to determine how many characters in a given font can fit on in a java.awt.TextArea that is a known number of pixels wide. BTW, the TextArea's getColumn() method, in this case, will return zero.

I know I can easily determine the number of pixels a string will be in width with a given font, but I'm not sure how to go the other direction: from pixel count to char count vs. char count to pixel count.

Can anyone help?

Rich
 
Rachel Swailes
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can only work out how many characters can by occupied in a certain number of pixels if you are using a monospaced font.

This is because an x and an i in a non-monospaced font take up a different number of pixels per character whereas a monospaced font takes up a defined number of pixels per character.

So for monospaced - find out the width of one character and then divide the pixels by that answer. (And for non-monospaced this won't work).

Cheers,
Rachel
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic