Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Trying to Figure out how to Specify a Font that's Guaranteed to be Monospaced

 
Kevin Simonson
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One of the really cool things I've noticed about Java is that it's very well defined. I write code and run it in one place, and then I run it in another place, and it does precisely the same thing. So when I upgraded my laptop to a new laptop I was surprised to discover that using a Font object on my old machine resulted in a monospaced font exactly like I wanted, but using a Font object defined exactly the same way on my new machine resulted in a variable width font. The code is:


That last comment means that I run this program by calling "java DrSt 0 10".

When I ran it on my old machine the letters, both upper case and lower case, fit snugly inside the drawn box; running it on my new machine, the lower case letters don't fill the box and the upper case letters overflow the box.

What I want is to be able to specify a monospaced font where I can predict ahead of time how much space it's going to take up, as a function of the width of the String object I'm using to call drawString() with.

Kevin S
 
Joe Areeda
Ranch Hand
Posts: 331
2
Java Netbeans IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Kevin,

I'm a bit surprised your new system doesn't have a Courier font. Just out of curiosity what OS is it?

If you look at http://docs.oracle.com/javase/6/docs/api/java/awt/Font.html you'll see that you can specify a "Font Family" of Monospaced instead of a specific font like Courier.

Also you can use the FontMetrics class to determine the exact size of a string before rendering if you want to be more adaptive.

Joe
 
Kevin Simonson
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Joe Areeda wrote:Hi Kevin,

I'm a bit surprised your new system doesn't have a Courier font. Just out of curiosity what OS is it?

If you look at http://docs.oracle.com/javase/6/docs/api/java/awt/Font.html you'll see that you can specify a "Font Family" of Monospaced instead of a specific font like Courier.

Also you can use the FontMetrics class to determine the exact size of a string before rendering if you want to be more adaptive.

Joe

My OS is Windows 7. Thanks for pointing me in the right direction; the new code is:

Isn't it pretty?

Kevin S
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic