It's not a secret anymore!
The moose likes Swing / AWT / SWT and the fly likes Right-justifying non-monospaced fonts in Graphics2D Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Reply Bookmark "Right-justifying non-monospaced fonts in Graphics2D" Watch "Right-justifying non-monospaced fonts in Graphics2D" New topic
Author

Right-justifying non-monospaced fonts in Graphics2D

Chris Crawford
Ranch Hand

Joined: Jun 22, 2011
Posts: 64

The original Macintosh OS 1 had, in its toolbox, a function that would return the length, in pixels, of any string to be drawn in the font currently assigned to the graphics port. This made it easy to center or right-justify any text in any font. After much searching, I have been unable to locate anything comparable in Java. There's plenty of stuff for right-justifying monospaced fonts, but this is trivial to do by hand. I found two topics here addressing right-justification of text, but both were for monospaced fonts. There's also lots of stuff for right-justifying stuff in Swing components, but I'm working directly in a Graphics2D environment.

I appreciate that there's a problem in that a user's computer cannot be guaranteed to have any particular font in its library, but cannot the web-standard fonts be assumed to be available?

Is this problem devoid of a solution?
Darryl Burke
Bartender

Joined: May 03, 2008
Posts: 4163
    
    3

Have you looked at java.awt.font.TextLayout?

And since this is related to GUIs I shall move it to a more appropriate section.


luck, db
There are no new questions, but there may be new answers.
Chris Crawford
Ranch Hand

Joined: Jun 22, 2011
Posts: 64

Damn! I should have been able to find that on my own. I went ten pages deep in a Google search and never saw that. Yes, that appears to be the perfect solution. Thanks much!
Darryl Burke
Bartender

Joined: May 03, 2008
Posts: 4163
    
    3

You're welcome. I can't remember the finer details, but somewhere in the internal size computations of TextLayout there's a 1-pixel bug (which may or may not be significant in your use case). Shall post the link to the old SDN thread if I can find in on the OTN.

edit: https://forums.oracle.com/forums/thread.jspa?messageID=5366659�
Chris Crawford
Ranch Hand

Joined: Jun 22, 2011
Posts: 64

No need for the reference for the 1-pixel error; I have a 5-pixel boundary that can absorb that. Thanks again.
Darryl Burke
Bartender

Joined: May 03, 2008
Posts: 4163
    
    3

Read that only after I'd found and added the link
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Right-justifying non-monospaced fonts in Graphics2D
 
Similar Threads
Text in different colours
Monospaced Font
Monospaced font on a JMenuItem
load/use fonts on linux
Why the result of printing out the not-letter chars to console is different from to applets